class Solution {
public:
int strStr(string haystack, string needle) {
int hlen=haystack.length();
int nlen=needle.length();
if(hlen<nlen)
return -1;
if(nlen==0)
return 0;
vector<int> next(nlen,0);
getNext(needle,next);
int i=0;
int j=0;
while(i<hlen&&j<nlen)
{
if(j==-1||haystack[i]==needle[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j==nlen)
return i-j;
return -1;
}
void getNext(string s,vector<int>& next){
int j=-1;
int i=0;
int len=s.length();
next[i]=j;
while(i<len-1)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
};