-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
51 lines (47 loc) · 857 Bytes
/
Copy pathKMP.cpp
File metadata and controls
51 lines (47 loc) · 857 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
#include<string>
using namespace std;
int next[1000+5];
void get_next(string t) //求模式串T的next函数值
{
int j=1, k=0;
next[1]=0;
while (j<t.length()) //模式串t的长度
if (k==0||t[j-1]==t[k-1])
next[++j]=++k;
else
k=next[k];
for(int i=1;i<=t.length();i++)
cout<<next[i]<<" ";
}
int KMP(string s,string t,int pos)
{
get_next(t);
int i=pos,j=1,sum=0;
int slen=s.length();
int tlen=t.length();
while(i<=slen&&j<=tlen)
{
sum++;
if(s[i-1]==t[j-1]) //如果相等,则继续比较后面的字符
{
i++;
j++;
}
else
j=next[j]; //j回退到next[j]
}
cout<<"一共比较了"<<sum<<"次"<<endl;
if (j>tlen) // 匹配成功
return i-tlen;
else
return 0;
}
int main()
{
string s,t;
int pos;
cin>>s>>t>>pos;
cout<<KMP(s,t,pos)<<endl;
return 0;
}