-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP_string_match.cpp
More file actions
56 lines (48 loc) · 1.11 KB
/
KMP_string_match.cpp
File metadata and controls
56 lines (48 loc) · 1.11 KB
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
52
53
54
55
56
#include<bits/stdc++.h>
using namespace std;
const int maxx = 1000005;
int failureTable[maxx];
void failureTableGenerate(string pattern){
int len = pattern.length();
failureTable[0]=failureTable[1]=0;
int i=1,j=0;
while(i<len){
if(pattern[i]==pattern[j])
failureTable[i++]=++j;
else{
if(j==0) failureTable[i++]=0;
else j=failureTable[j-1];
}
}
}
int KMP(string text,string pattern){
int n = text.length();
int m = pattern.length();
failureTableGenerate(pattern);
int i=0,j=0,cnt=0;
while(i<n){
if(text[i]==pattern[j]){
i++,j++;
if(j==m){
j = failureTable[j-1];
cnt++;
}
}
else {
if(j!=0) j = failureTable[j-1];
else i++;
}
}
return cnt;
}
int main(){
int test,cs=1;
scanf("%d",&test);
while(test--){
memset(failureTable,-1,sizeof failureTable);
string text,pattern;
cin>>text>>pattern;
printf("Case %d: %d\n",cs++,KMP(text,pattern));
}
return 0;
}