28. 找出字符串中第一个匹配项的下标

KMP算法

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         int* next = getNext(needle);
 5         int j = 0;  // j是前缀的末尾
 6         for(int i = 0; i < haystack.size(); i++){   // i是后缀的末尾
 7             while(j > 0 && haystack[i] != needle[j])
 8                 j = next[j-1];
 9             if(haystack[i] == needle[j])
10                 j++;
11             if(j == needle.size())
12                 return i - j + 1;
13         }
14         return -1;
15     }
16 private:
17     int* getNext(string needle){
18         int len = needle.size();
19         int next[len];
20         next[0] = 0;
21         int j = 0;
22         for(int i = 1; i < len; i++){
23             while(j > 0 && needle[i] != needle[j])  // 前后缀不同
24                 j = next[j-1];   // 向前回退.
25             if(needle[i] == needle[j])
26                 j++;
27             next[i] = j;
28         }
29         return next;
30     }
31 };

459. 重复的子字符串

直接找s的next数组,然后判断s的长度是否可以整除n-next[n-1]

 1 class Solution {
 2 public:
 3     bool repeatedSubstringPattern(string s) {
 4         int n = s.size();
 5         int* next = getNext(s);
 6         return next[n-1] != 0 && n%(n-next[n-1]) == 0;
 7     }
 8 private:
 9     int* getNext(string s){
10         int n = s.size();
11         int next[n];
12         next[0] = 0;
13         int j = 0;
14         for(int i = 1; i < n; i++){
15             while(j > 0 && s[i] != s[j])
16                 j = next[j-1];
17             if(s[i] == s[j])    j++;
18             next[i] = j;
19         }
20         return next;
21     }
22 };