Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
实现KMP
class Solution { public: char *strStr(char *haystack, char *needle) { // Start typing your C/C++ solution below // DO NOT write int main() function if(haystack==NULL||needle==NULL)return NULL; if(needle[0]=='')return haystack; int len=0; for(;;){if(needle[len]=='')break;len++;} vector<int> dict; dict.resize(len); dict[0]=-1; dict[1]=0; for(int i=2;i<len;i++){ int j=dict[i-1]; while(j>=0&&needle[j]!=needle[i-1]){ j=dict[j]; } if(j<0)j=0; else if(needle[j]==needle[i-1]){ j++; } dict[i]=j; } int i=0,j=0; while(haystack[i]!='') { while(j>=0&&haystack[i]!=needle[j]){ j=dict[j]; } j++; if(j==len){ return &haystack[i-len+1]; } i++; } return NULL; } };