[leetcode]Implement strStr()

不知道为毛,在函数里面每次开vector作为next就要re。。。

改了才过,但是代码不好看啊。。。

用kmp求解

kmp的重点就是next数组

next[i]表示i结尾的后缀匹配的最长前缀

如果i匹配失败,我们就不用从头开始匹配的,因为i前面那段已经匹配了

利用next来移动这个串的位置

http://whocouldthat.be/visualizing-string-matching/ 这个演示不错

vector<int> f(1000000);
class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(haystack == nullptr || needle == nullptr) return nullptr;
        int lenn = strlen(needle);
        if(lenn == 0) return haystack;
        fill(f.begin() , f.begin() + lenn , 0);
        get_next(f , needle , lenn);
        int i = 0;
        while(*haystack && i < lenn) {
            if(i == -1 || *haystack == needle[i]) {
                i++;
                haystack++;
            } else {
                i = f[i];
            }
        }
        if(i == lenn) return haystack - lenn;
        else return nullptr;
    }
private:
    void get_next(vector<int>&next , char* needle ,int len) {
        //int len = next.size();
        int pre = -1 , last = 0;
        next[0] = -1;
        while(last < len) {
            if(pre == -1 || needle[pre] == needle[last]) {
                pre++;last++;
                next[last] = pre;
            } else {
                pre = next[pre];
            }
        }
    }
};

 代码中的求next函数

last指向的next值已经算出来了的。。。因为前面比较好了,就能确定下一个的跳转了

比较当前的last和pre,然后确定next[last+1]

原文地址:https://www.cnblogs.com/x1957/p/3524684.html