KMP

//
// Created by Administrator on 2021/8/11.
//

#ifndef C__TEST02_KMP_HPP
#define C__TEST02_KMP_HPP

#include <iostream>
#include <vector>
using namespace std;

class KMP {
public:
    static int getIndexOfSubString(string s1, string s2){
        if(s1.empty() || s2.empty() || s1.size() < s2.size()){
            return -1;
        }
        vector<int> next = getNextArray(s2);
        int i1 = 0;
        int i2 = 0;

        while(i1 < s1.size() && i2 < s2.size()){
            if(s1[i1] == s2[i2]){
                i1++;
                i2++;
            }else if(next[i2] == -1){
                i1++;
            }else{
                i2 = next[i2];
            }
        }
        return i2 == s2.size()? (i1 - i2):-1;
    }
    static vector<int> getNextArray(string s){
        if(s.size() == 1){
            return {-1};
        }
        vector<int> next(s.size());
        next[0] = -1;
        next[1] = 0;
        int cn = 0;
        for(int i = 2; i < s.size(); ++i){
            if(s[i-1] == cn){
                next[i++] = ++cn;
            }else if(cn > 0){
                cn = next[cn];
            }else{
                next[i++] = 0;
            }
        }
        return next;
    }
};


#endif //C__TEST02_KMP_HPP

上一篇:KMP


下一篇:MySQL备份