标签:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
比较容易想到的是直接匹配,即用needle从haystack的开始处匹配,成功则返回,不成功继续下一次匹配。
1 int strStr(char *haystack, char *needle) 2 { 3 int i = 0, j = 0; 4 int m = strlen(haystack); 5 int n = strlen(needle); 6 int *match_table = new int[n + 1]; 7 generate_match_table(needle, match_table); 8 9 while (i < m && j < n) 10 { 11 if (haystack[i] == needle[j]) 12 { 13 i++; 14 j++; 15 } 16 else 17 { 18 i = i - j + 1; 19 j = 0; 20 } 21 } 22 23 return ((j == n) ? (i - j): -1); 24 }
时间复杂度O(m * n)
KMP算法可以达到O(m + n)的复杂度:
1 int strStr(char *haystack, char *needle) 2 { 3 int i = 0, j = 0; 4 int m = strlen(haystack); 5 int n = strlen(needle); 6 int *match_table = new int[n + 1]; 7 generate_match_table(needle, match_table); 8 9 while (i < m && j < n) 10 { 11 if (haystack[i] == needle[j]) 12 { 13 i++; 14 j++; 15 } 16 else 17 { 18 i = i - match_table[j]; 19 j = 0; 20 } 21 } 22 23 return ((j == n) ? (i - j): -1); 24 } 25 26 void generate_match_table(char *P, int match_table[]) 27 { 28 int n = strlen(P); 29 int j, k; 30 match_table[0] = -1; 31 k = match_table[0]; 32 33 j = 0; 34 while (j < n) 35 { 36 if (k == -1 || P[j] == P[k]) 37 { 38 k++; 39 j++; 40 match_table[j] = k; 41 } 42 else 43 { 44 k = match_table[k]; 45 } 46 } 47 }
勒etcode 28. Implement strStr()
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4249000.html