思路
- 使用 KMP算法
Code
class Solution {
public:
int f[10000] = { 0 };
int strStr(string haystack, string needle) {
int n = haystack.length(), m = needle.length();
{
int i = 0, j = -1;
f[0] = -1;
while (i < m-1)
{
if (j == -1 || needle[i] == needle[j])
{
f[++i] = ++j;
}
else
j = f[j];
}
}
int i=0,j=0;
while (i<n)
{
if (haystack[i] == needle[j])
{
++i, ++j;
}
else if(j>0)
{
j = f[j];
}
else ++i;
if (j ==m) return i - j;
}
return -1;
}
};