Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
此题我觉得并不是真要你写出kmp算法。 指针暴力法我觉得可能是考察点。而且要accept的话,必须要忽略后面一段不可能匹配的串。指针的操作要非常小心。
Of course, you can demonstrate to your interviewer that this problem can be solved using known efficient algorithms such as Rabin-Karp algorithm, KMP algorithm, and the Boyer-Moore algorithm. Since these algorithms are usually studied in advanced algorithms class, for an interview it is sufficient to solve it using the most direct method — The brute force method.
非指针代码很好小,很难有错。最长扫描n1-n2+1个就够了。
1 class Solution { 2 public: 3 char *strStr(char *haystack, char *needle) { 4 if (haystack == NULL || needle == NULL) return NULL; 5 int n1 = strlen(haystack); 6 int n2 = strlen(needle); 7 int j; 8 9 for (int i = 0; i < n1 - n2 + 1; ++i) { 10 j = 0; 11 while (j < n2 && needle[j] == haystack[i + j]) j++; 12 if (j == n2) return haystack + i; 13 } 14 return NULL; 15 } 16 };
c指针代码:
1 class Solution { 2 public: 3 char *strStr(char *haystack, char *needle) { 4 if (haystack == NULL || needle == NULL) return NULL; 5 if (*needle == '