Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
Solution:
class Solution {
public:
void getNext(string needle, vector<int> &next)
{
int i = 0, j = -1;
next[i] = j;
while(i < needle.length())
{
while(j != -1 && needle[i] != needle[j]) j = next[j];
next[++i] = ++j;
}
}
int strStr(string haystack, string needle) {
vector<int> next(needle.length()+1);
getNext(needle, next);
int i = 0, j = 0;
int hlen = haystack.length();
int nlen = needle.length();
while(i < hlen && j < nlen)
{
if(j == -1 || haystack[i] == needle[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j == nlen) return i - j;
else return -1;
}
};