-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
74 lines (70 loc) · 1.1 KB
/
Copy pathKMP.cpp
File metadata and controls
74 lines (70 loc) · 1.1 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
int KMP(string s,string p)
{
int i=0,j=0;
vector<int>next=getnext(p);
while (i<s.size()&&j<(int)p.size())
{
if(j==-1||s[i]==p[j])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j==p.size())
{
return i-j;
}
else
{
return -1;
}
}
vector<int>getnext(string p)
{
int i=0,j=-1;
vector<int>next(p.size(),0);
next[0]=-1;
while (i<(int)p.size()-1)
{
if(j==-1||p[i]==p[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
return next;
}
vector<int>getnextnext(string p)
{
vector<int>next(p.size());
next[0]=-1;
int i=0,j=-1;
while(i<p.size()-1)
{
if(j==-1||p[i]==p[j])
{
if(p[++i]==p[++j])
{
next[i]=next[j];
}
else
{
next[i]=j;
}
}
else
{
j=next[j];
}
}
return next;
}