Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:
KMP算法。
这道题理解KMP花了很久的时间,在求next函数的时候使用递推的思路,假如a[i] = k, 如果a[i+1] = a[k],那么a[i+2] != a[k+1]时,a[i+1] = k+1, 否则k = next[k],相当于在已匹配的子串部分再使用KMP。理解这一部分就基本理解全部了。
代码:
1 void getNext(char *needle, int length, int *next){ 2 next[0] = -1; 3 int k = -1; 4 int i = 0; 5 while(i < length-1){ 6 if(k == -1 || needle[i] == needle[k]){ 7 k++; 8 i++; 9 if(needle[i] != needle[k]) 10 next[i] = k; 11 else 12 next[i] = next[k]; 13 } 14 else 15 k = next[k]; 16 } 17 } 18 char *strStr(char *haystack, char *needle) { 19 // IMPORTANT: Please reset any member data you declared, as 20 // the same Solution instance will be reused for each test case. 21 int lh = strlen(haystack), ln = strlen(needle); 22 if(ln == 0 || lh == 0) 23 return NULL; 24 int *next = new int[ln]; 25 getNext(needle, ln, next); 26 int i=0,j=0; 27 while(i < lh && j < ln){ 28 if(haystack[i] == needle[j]){ 29 i++; 30 j++; 31 } 32 else{ 33 j = next[j]; 34 if(j == -1){ 35 j = 0; 36 i++; 37 } 38 } 39 } 40 delete[] next; 41 if(j == ln){ 42 return haystack+i-ln; 43 } 44 else 45 return NULL; 46 }