题意
求p串在s串中的出现位置
思路
扩展KMP算法,时间复杂度:O(n)
代码
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
int next[100005];
next[0] = -1;
int i = 0, j = -1;
while (i < needle.size())
{
if (j == -1 || needle[i] == needle[j])
{
next[++i] = ++j;
if (needle[i] == needle[next[i]]) next[i] = next[next[i]];
}
else
j = next[j];
}
i = 0, j = 0;
while (i < haystack.size())
{
if (j == -1 || haystack[i] == needle[j])
{
++i, ++j;
if (j == needle.size())
return i - needle.size();
}
else
j = next[j];
}
return -1;
}
};