-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.cpp
63 lines (59 loc) · 941 Bytes
/
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
#include "cstdio"
#include "iostream"
#include "cstring"
using namespace std;
int ne[20];///这个数组中盛放的是匹配字符串的next值
void GetNext(char *a)///这个函数是为了标记匹配字符串的next值
{
int len = strlen(a);///先求字符串的长度,便于循环赋值
int i = 0, j = -1;
ne[0] = -1;
while (i < len)
{
if (j == -1 || a[i] == a[j])
{
++i;
++j;
if (a[i]!=a[j])
{
ne[i] = j;
}
else
{
ne[i] = ne[j];
}
}
else j = ne[j];
}
}
///实际上每求一个next值要循环两遍
int KMP(char *a, char *b)
{
int lena = strlen(a);
int lenb = strlen(b);
int i = 0, j = 0;
while (i < lena && j < lenb)
{
if (j == -1 || a[i] == b[j])
{
j++;
i++;
}
else
j = ne[j];
}
if (j == lenb)
return i - j + 1;
else
return -1;
}
int main()
{
char s[100];///this is the main
char f[100];///this is the one to be found
scanf("%s", &s);
scanf("%s", &f);
GetNext(f);
cout << KMP(s, f) << endl;
return 0;
}