-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path28.implement_strstr.cpp
50 lines (48 loc) · 1.12 KB
/
28.implement_strstr.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
//coding:utf-8
/******************************************
Program: strstr
Description:
Shanbo Cheng: [email protected]
Date: 2016-07-25 14:11:22
Last modified: 2016-07-25 14:34:42
GCC version: 4.7.3
std = C++ 11
******************************************/
//KMP algorithm
class Solution {
public:
int strStr(string haystack, string needle) {
const int len = needle.length();
int next[len];
getNext(needle, next);
int i = 0;
int j = 0;
while (i < haystack.length() && j < len){
if (j == -1 || haystack[i] == needle[j]){
i++;
j++;
}
else
j = next[j];
}
if (j == len)
return i - j;
else
return -1;
}
void getNext(string p, int next[]){
int pLen = p.length();
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1){
if (k == -1 || p[j] == p[k]){
++k;
++j;
next[j] = k;
}
else
k = next[k];
}
}
};