forked from codersinghal/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp.cpp
59 lines (54 loc) · 1.05 KB
/
kmp.cpp
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
57
58
59
KMP algo worstcase-O(n)
void kmp(string text,string pat)
{ int cnt=0;
int n=text.length();
int m=pat.length();
int lps[m];
computeLPS(pat,m,lps);
int i=0,j=0;
while(i<n)
{
if(text[i]==pat[j])
{
i++;
j++;
}
if(j==m)
{
cnt++;
j=lps[j-1];
}
else
if(i<n&&text[i]!=pat[j])
{
if (j != 0)
j = lps[j - 1];
else
i++;
}
}
}
void computeLPS(string pat,int m,int *lps)
{
int len = 0;
lps[0] = 0; // lps[0] is always 0
int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if (len != 0) {
len = lps[len - 1];
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}