KMP算法记录
作者:
V1
,
2022-04-27 15:23:04
,
所有人可见
,
阅读 191
//关于Carl大佬的kmp算法实现,对它的理解还有待加强
class Solution {
public:
//构造next数组的函数
void getNext(int* next,const string& s)
{
//对next数组进行初始化
int j = 0;
next[0] = 0;
for(int i = 1 ; i < s.size() ; i++)
{
//情况一:i与j对应的元素值不相等
//使用while循环进行连续回退,直到回退到相等为止
while(j > 0 && s[i] != s[j])
{
j = next[j - 1];
}
//情况二:i与j对应的元素相等
//i与j同时++就行了,这里只有j++,i在for循环一轮之后自动++
if(s[i] == s[j])
{
j++;
}
next[i] = j;
}
return ;
}
//使用next数组进行匹配的函数
int strStr(string haystack, string needle) {
if(needle.size() == 0)
{
return 0;
}
int next[needle.size()];
getNext(next,needle);
int j = 0;
for(int i = 0 ; i < haystack.size() ; i++)
{
while(j > 0 && haystack[i] != needle[j])
{
j = next[j - 1];
}
if(haystack[i] == needle[j])
{
j++;
}
if(j == needle.size())
{
return (i - needle.size() + 1);
}
}
return -1;
}
};