Skip to content

Commit 5a2b2f4

Browse files
committed
kmp
1 parent d052cd0 commit 5a2b2f4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

String Matching/kmp.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
3+
vector<int>table;
4+
5+
void pre(string&a){
6+
table.assign(a.size() , 0);
7+
table[0] =-1;
8+
int j=-1 , i = 0;
9+
while(i < (int)a.size()){
10+
while(j>=0 && a[i] != a[j]){
11+
j = table[j];
12+
}
13+
++j;
14+
++i;
15+
table[i] = j;
16+
}
17+
}
18+
19+
void search(string &a , string &b){
20+
pre(a);
21+
int i=0 , j = 0;
22+
while(i < (int)b.size()){
23+
while(j >= 0 && b[i] != a[j]){
24+
j = table[j];
25+
}
26+
++j;
27+
++i;
28+
if(j==(int)a.size()){
29+
cout << i - j << ' ' ;
30+
j = table[j];
31+
}
32+
}
33+
cout << '\n';
34+
}
35+

0 commit comments

Comments
 (0)