KMP:
using namespace std;
int nex[N];
class Solution {
void get_next(char *pat){
MM(nex,-1);
for(int i=1,k; pat[i]; i++){
for( k=nex[i-1]; k>=0 && pat[i]!=pat[k+1];k=nex[k]);
if (pat[k+1]==pat[i]) nex[i] = k+1;
}
}
public:
int strStr(char *haystack, char *needle) {
int i=0,j=0;
get_next(needle);
while(haystack[i] && needle[j]){
if (needle[j] == haystack[i]) i++,j++;
else if (j==0) i++;
else j= nex[j-1] +1;
}
if (needle[j]) return -1;
else return i-j;
}
};