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) {
if (haystack.empty()) return needle.empty() ? 0 : -1;
if (needle.empty()) return 0;
vector<int> next(needle.length() + 1);
getNext(next, needle);
int i = 0, j =-1;
for (i=0;i< haystack.length();i++)
{
while (j != -1 && haystack[i] != needle[j+1])
j = next[j];
if(haystack[i]==needle[j+1])
j++;
if(j==needle.length()-1)
return i-j;
}
return -1;
}
void getNext(vector<int> &next, string &needle) {
int i = 0, j = -1;
next[i] = j;
for(i=1;i!=needle.length();i++)
{
while (j != -1 && needle[i] != needle[j+1])
j = next[j];
if (needle[i] == needle[j+1]) j++;
next[i] = j;
}
}
};