-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp.cpp
71 lines (68 loc) · 1.38 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
60
61
62
63
64
65
66
67
68
69
70
71
#include<iostream>
#include<cstring>
using namespace std;
char s1[1000001];
char s2[1000001];
int kmpnext[1000001];
// definition of kmpnext[i]: the maximum length of the common string of the prefix and suffix of s2[0:i] (inclusive)
// if index starts from 1, change the definition to the maximum length of ... s2[1:i] (inclusive)
// if index starts from 1, just offset every index by 1 and change every 0 into 1 (marked offset).
void getkmpnext(int l2)
{
// in preprocessing, i starts from 1 and j from 0, since there's no point matching the whole string with itself.
int i=1, j=0; // offset
kmpnext[0] = 0;
while(i<l2)
{
if(s2[i] == s2[j])
{
kmpnext[i] = j+1;
i++;
j++;
}
else if(j>0) // offset
{
j = kmpnext[j-1];
}
else //j = 0 and s2[i]!=s2[j]
{
kmpnext[i]=0; // offset
i++;
}
}
}
void kmp(int l1, int l2)
{
// in real matching, i and j both start from 0.
int i=0,j=0; // offset
while(i<l1)
{
if(s1[i] == s2[j]) // if current character matches, continue matching
{
i++;
j++;
if(j==l2) // finished matching
{
cout<<i-l2<<endl;
j = kmpnext[j-1];
}
}
else if(j>0) // offset, if match is broken, move j back to the next possible position
{
j = kmpnext[j-1];
}
else //j = 0 and s1[i]!=s2[j]
{
i++;
}
}
}
int main()
{
cin>>s1;
cin>>s2;
int l1 = strlen(s1);
int l2 = strlen(s2);
getkmpnext(l2);
kmp(l1, l2);
}