因为是道简单题,所以最简单的字符串匹配应该也能过,但还是练习一下KMP算法为好。KMP算法的介绍可以参考这篇
以后有时间试试Boyer-Moore算法
代码:
1 int strStr(char *haystack, char *needle) { 2 if (!needle[0]) return 0; 3 int n = strlen(needle); 4 int *next = new int[n + 1]; 5 int i, j; 6 7 i = 0; 8 j = -1; 9 next[0] = -1; 10 while (needle[i]) { 11 if (j < 0 || needle[i] == needle[j]) { 12 i++; 13 j++; 14 next[i] = j; 15 } 16 else 17 j = next[j]; 18 } 19 20 i = 0; 21 j = 0; 22 while (haystack[i] && j < n) { 23 if (j < 0 || haystack[i] == needle[j]) { 24 i++; 25 j++; 26 } 27 else 28 j = next[j]; 29 } 30 31 return j == n ? i - n : -1; 32 }