-
Notifications
You must be signed in to change notification settings - Fork 0
/
28_Implement_strStr.cpp
57 lines (46 loc) · 1.28 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
51
52
53
54
55
56
57
class Solution {
// KMP implement
public:
// 算出prefix table,然後當作next table
void getNext(int* next, const string pattern) {
int patLen = pattern.size();
int i, j;
j = 0;
next[0] = j;
for (i = 1; i < patLen; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j-1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
}
// haystack : 原文字串
// needle : pattern
int strStr(string haystack, string needle) {
int textLen = haystack.size();
int patLen = needle.size();
int* next = NULL;
int i, j;
if (patLen == 0) {
return 0;
}
next = new int[patLen];
getNext(next, needle);
j = 0;
for (i = 0; i < textLen; i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j-1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == patLen) {
return (i - patLen + 1);
}
}
return -1;
}
};