class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(m==0)
return 0;
vector<int> next = getNext(needle);
for(int i=0, j=0; i<n; i++)
{
// i 指向文本串的指针
// j 指向模式串的指针
while(j>0 && haystack[i]!=needle[j])
j = next[j-1];
if(haystack[i]==needle[j])
j++;
if(j==m)
return i-m+1;
}
return -1;
}
vector<int> getNext(const string& str)
{
// 前缀函数,next[i] 的值表示字符串 str[i] 中的最长相等前后缀的长度
int strSize = str.size();
vector<int> next(strSize, 0); // 前缀函数使用 0 作为初始化
for (int i = 1, j = 0; i < strSize; i++)
{
// j 指向前缀末尾位置
// i 指向后缀末尾位置
while (j > 0 && str[i] != str[j])
j = next[j - 1]; // 如何理解这一步?用前面匹配的信息来回到最近可能相等的地方后继续匹配
if (str[i] == str[j])
j++;
next[i] = j;
}
return next;
}
};
KMP算法
最新推荐文章于 2024-05-31 17:17:25 发布