代码随想录算法训练营第9天|28

97 阅读1分钟

学习资料

代码随想录+左程云算法体系课

28

感觉左神版本的讲的更通透一些,这里将左神版本的c++ 版提交

class Solution {
public:
    vector<int> getNextArray(string str2) {
        if (str2.size() == 1) {
            return vector<int>({-1});
        }
        vector<int> next = vector<int>(str2.size());
        next[0] = -1;
        next[1] = 0;
        int i = 2;
        int cn = 0;
        while( i < next.size()) {
            if (str2[i - 1] == str2[cn]) {
                next[i++] = ++cn;
            } else if (cn > 0) {
                cn = next[cn];
            } else {
                next[i++] = 0;
            }
        }
        return next;

    }
    int strStr(string haystack, string needle) {
        if (haystack.size() < needle.size()) {
            return -1;
        }
        vector<int> next = getNextArray(needle);
        int x = 0;
        int y = 0;
        while ( x < haystack.size() && y < needle.size()){
            if ( haystack[x] == needle[y]){
                x++;
                y++;
            }else if (next[y] == -1) {
                x++;
            }else {
                y = next[y];
            }
        }
        return y == needle.size() ? x - y : -1;


    }
};