-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28_kmp.cpp
More file actions
63 lines (56 loc) · 1.19 KB
/
28_kmp.cpp
File metadata and controls
63 lines (56 loc) · 1.19 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
#include<vector>
#include<string>
#include<iostream>
using namespace std;
vector<int> next_array;
void build_next(string p){
next_array = vector<int>(p.length());
next_array[0] = -1;
int k = -1;
int j = 0;
int plen = p.length();
while (j < plen - 1){
if (k == -1 || p[j] == p[k]){
k++, j++;
if (p[j] != p[k])
next_array[j] = k;
else
next_array[j] = next_array[k];
}else{
k = next_array[k];
}
}
}
int kmp(string s, string p){
int i = 0;
int j = 0;
int slen = s.length();
int plen = p.length();
while (i < slen && j < plen){
if (j == -1 || s[i] == p[j]){
i++;
j++;
}else{
j = next_array[j];
}
}
if (j == p.length())
return i - j;
return -1;
}
int strStr(string haystack, string needle) {
build_next(needle);
return kmp(haystack, needle);
}
void testCase(){
if (strStr("hello", "ll") != 2)
cout << "wrong";
else cout << "right";
cout << endl;
}
int main(){
testCase();
// for (auto k:next_array)
// cout << k << endl;
return 0;
}