0 求pattern串在原串str中是否存在,如果存在就返回下标
1 kmp算法,先求next数组,然后逐个向后匹配即可。kmp算法的讲解本人写的在这里 https://blog.csdn.net/mistakk/article/details/83114497 。
2 代码
int strStr(string haystack, string needle)
{
int n = needle.size();
if (n == 0)
return 0;
vector<int> table(n, 0);
table[0] = -1;
for (int i = 1; i < n; ++i)
{
int k = table[i - 1];
while (k != -1 && needle[k] != needle[i-1])
k = table[k];
table[i] = k + 1;
}
int size1 = haystack.size(), size2 = needle.size();
int i = 0, j = 0;
while ((i < size1) && (j < size2))
{
if (j==-1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
{
j = table[j];
}
}
if (j == needle.size())
return i - j;
else
return -1;
}
3 分析
3.1 先求next数组,然后再顺序匹配,比较简单;在实现上,要注意先把两者的长度进行标识出来,然后再写循环。否则j是可能为-1的,而vec.size()返回的是size_t类型,是无符号数,在用-1与之比较时,会隐式类型转换为size_t类型,那就是最大的size_t了,从而造成循环提前退出而报错。