[leetcode] 21. Implement strStr()
这个题目是典型的KMP算法,当然也可以试试BM,当然有关KMP和BM的介绍阮一峰曾经写过比较好的科普,然后july也有讲解,不过那个太长了。
先放题目吧:
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 *
orString
, please click the reload button to reset your code definition.
就是找到haystack内是否有needle这个字符串,字符串查找算法。
KMP主要是建立一个next的部分匹配数组,来用空间换时间。next的生成函数是KMP关键,解法如下:
class Solution { public: vector<int> generateNext(char *str) { int len = strlen(str); vector<int> tmp; tmp.push_back(0); for (int i = 1, j = 0; i < len; i++) { while (j > 0 && str[i] != str[j]) { j = tmp.at(j - 1); } if (str[i] == str[j]) { j++; } tmp.push_back(j); } return tmp; } int strStr(char *haystack, char *needle) { vector<int> next = generateNext(needle); int lenH = strlen(haystack); int lenN = strlen(needle); if (lenN == 0) { return 0; } if (lenH < lenN) { return -1; } int i, j; for (i = 0, j = 0; i < lenH; i++) { while (j > 0 && haystack[i] != needle[j]) { j = next[j - 1]; } if (haystack[i] == needle[j]) { j++; } if (j == lenN) { return i - lenN + 1; } } return -1; } };