0%

KMP改进

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
void getNext(string substr, int next[])
{
int i = 0,j = -1;
next[0] = -1;
while (i<substr.length() - 1)
{
if (j == -1 || substr[i] == substr[j])
{
++i;
++j;
/*next[i] = j;*/
if (substr[i] != substr[j])
{
next[i] = j;
}
else
{
next[i] = next[j];
}
}
else
j = next[j];
}
}
int KMP(string str, string substr)
{
int* next = new int[substr.length()];
getNext(substr, next);
int i = 0,j = 0;
while (i<str.length() && j<substr.length())
{
if (j == -1 || str[i] == substr[j])
{
++i;
++j;
}
else
{
j = next[j];
}

}
if (j >= substr.length())
{
return i - substr.length();
}
return -1;
}