kmp算法
根据《算法导论》上的伪代码修改,书上的字符串索引从1开始,需要修改为从0开始
1 class Solution {
2 public:
3 int strStr(string haystack, string needle) {
4 int sz1 = haystack.size(), sz2 = needle.size();
5 if (sz2 == 0) {
6 return 0;
7 }
8 if (sz1 == 0) {
9 return -1;
10 }
11 int q = -1;
12 vector<int>trans = _helper(needle);
13 for (int i = 0; i < sz1; ++i) {
14 while (q > -1 && haystack[i] != needle[q+1]) {
15 q = trans[q];
16 }
17 if (haystack[i] == needle[q+1]) {
18 ++q;
19 }
20 if (q == sz2-1) {
21 return i - sz2+1;
22 }
23 }
24 return -1;
25 }
26 private:
27 vector<int> _helper(string needle) {
28 int sz = needle.size();
29 vector<int>res(sz, 0);
30 int k = -1;
31 res[0] = -1;
32 //q表示状态
33 for (int q = 1; q < sz; ++q) {
34 while (k > -1 && needle[k+1] != needle[q]) {
35 k = res[k];
36 }
37 if (needle[q] == needle[k+1]) {
38 ++k;
39 }
40 res[q] = k;
41 }
42 return res;
43 }
44 };