Implement strStr() kmp算法

用这题复习下kmp算法。kmp网上坑爹的是有很多种匹配方式,容易混淆,,后人要警惕啊。这里对要查找的字符串的next全部置为-1,预处理时i和next[i-1]+1相比较。和 这里相似。预处理完再匹配,第i个字符不匹配则比较第next[i-1]+1个。

class Solution{public:char *strStr(char *haystack, char *needle){if(haystack == NULL || needle == NULL)return NULL;int sz = strlen(needle);vector<int>next(sz,-1);for(int i = 1; i < sz; i++){int index = i – 1;while(index != -1 && needle[next[index]+1] != needle[i])index = next[index];next[i] = index==-1?-1:next[index]+1;}int i = 0;while(*haystack && i <sz){while(i != -1 && *haystack != needle[i])i = i==0?-1:next[i-1]+1;haystack++;i++;}return i < sz?NULL:haystack-sz;}};/*                    a b C b C a d                    -1 -1 -1 -1 -1 0 -1                    abcab cabdabba                      a   b  c  a  b  d                     -1 -1  -1 0  1  -1*/

可是旅行的彼时那刻我的心情一直是好的吗?

Implement strStr() kmp算法

相关文章:

你感兴趣的文章:

标签云: