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<vector>
#include<string>

using namespace std;

//未优化版本求next数组
void get_next(vector<int> &next, string s) {
int i=0, j=-1;
next[0] = -1;
while(i<s.length()-1) {
if(j ==-1 || s[i] == s[j]){
++i, ++j;
next[i] = j;
}
else {
j = next[j];
}
}
}

//优化版本求next数组
void get_nextval(vector<int> &next, string s) {
int i=0,j=-1;
next[0] = -1;
while(i<s.length() - 1) {
if(j == -1 || s[i] == s[j]) {
++i, ++j;
if(s[i] != s[j]) next[i] = j;
else next[i] = next[j];
}
else {
j = next[j];
}
}
}

int Index_KMP(string s1, string s2, vector<int> next) {
int i=0, j=0;
int len1 = s1.length();
int len2 = s2.length();
while(i < len1 && j < len2) {
if(j==-1 || s1[i] == s2[j]) {
++i, ++j;
}
else {
j = next[j];
}
}
if(j>=s2.length()) {
return i-s2.length();
}
else {
return 0;
}
}

int main() {
string s1 = "aabbccddeeff";
string s2 = "ccdd";
vector<int> next(4, 0);
// get_next(next, s2);
get_nextval(next, s2);
// for(int i=0;i<next.size();i++){
// cout << next[i] << " " << endl;
// }
int ind = Index_KMP(s1, s2, next);
cout << ind << endl;
return 0;
}