解题思路:
KMP模式匹配算法,先生成next数组,再对字符串进行匹配.
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
if(m == 0) return 0;
haystack.insert(haystack.begin(),' ');
needle.insert(needle.begin(),' ');
vector<int> next(m + 1);
//预处理next数组
for(int i = 2, j = 0; i <= m; i++){
while(j and needle[i] != needle[j + 1]) j = next[j];
if(needle[i] == needle[j + 1]) j++;
next[i] = j;
}
//匹配过程
for(int i = 1, j = 0; i <= n; i++){
while(j and haystack[i] != needle[j + 1]) j = next[j];
if(haystack[i] == needle[j + 1]) j++;
if(j == m) return i - m;
}
return -1;
}
};
运行结果: