Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution {
public:
int strStr(string haystack, string needle) {
const char* T = haystack.c_str();
const char* p = needle.c_str();
int n = (int)strlen(T), i = 0;//文本串指针
int m = (int)strlen(p), j = 0;//模式串指针
int *Next = new int[m];
int t = Next[0] = -1;//模式串指针
while (j<m - 1)
{
if (t<0 || needle[j] == needle[t])
{
Next[++j] = ++t;
}
else{
t = Next[t];
}
}
i = 0; j = 0;
while (i<n&&j<m)
{
if (j<0 || T[i] == p[j])
{
i++; j++;
}
else
{
j = Next[j];
}
}
delete[] Next;
if (j == m )
return i - j;
else
return -1;
}
};