就是一个普通的KMP,这里推荐一篇文章,我觉得写得非常好,没事可以经常翻出来看看
https://blog.csdn.net/gao506440410/article/details/81812163
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length() == 0) return 0;
if(haystack.length() == 0) return -1;
int next[11000000];
next[0] = -1;
int k = -1, j = 0;
int nlen = needle.length();
while(j < nlen){
if(k == -1 || needle[k] == needle[j]){
k++;
j++;
if(needle[k] == needle[j]) next[j] = next[k];
else next[j] = k;
}
else k = next[k];
}
int hlen = haystack.length();
j = 0;
int i = 0;
while(i < hlen && j < nlen){
if(j == -1 || haystack[i] == needle[j]){
i++;
j++;
}
else j = next[j];
}
if(j == nlen) return i - j;
else return -1;
}
};
写的时候注意几个问题
1.next数组的初始化一定不要忘
2.在这题里n串为空的判定一定要在h串前面,因为n串为空默认就在第0个位置上匹配了
明天尝试一下BM和Sunday算法