KMP
class Solution {
public:
vector<int> getnext(string s){
int n = s.size();
vector<int> next(n);
int i=0,j=-1;
next[0]=-1;
while(i<n-1){
if(j==-1 || s[i]==s[j]){
++i;
++j;
next[i]=j;
}else{
j=next[j];
}
}
return next;
}
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
if(haystack.empty()) return -1;
int n1 = haystack.size();
int n2 = needle.size();
vector<int> next(getnext(needle));
int i=0,j=0;
while(i<n1 && j<n2){
if(j==-1 || haystack[i]==needle[j]){
++i;
++j;
}else{
j=next[j];
}
}
return (j==n2)?(i-j):-1;
}
};