KMP算法

思路:详见程序员面试指南

代码如下:

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

vector<int>getNextarray(string pat){
    if (pat.size() == -1)return{ -1 };
    vector<int>next(pat.size(), 0);
    next[0] = -1;
    next[1] = 0;
    int cn = 0;
    int pos = 2;
    while (pos < pat.size()){
        if (pat[pos - 1] == pat[cn]){
            next[pos++] == ++cn;
        }
        else if (cn>0){
            cn = next[cn];
        }
        else{
            next[pos++] = 0;
        }
    }
    return next;
}
int getIndext(string str, string pattern){
    if (str.size() == 0 || pattern.size() == 0 || str.size() < pattern.size())return -1;
    int si = 0;
    int pi = 0;
    vector<int>next = getNextarray(pattern);
    while (si < str.size() && pi < pattern.size()){
        if (str[si] == pattern[pi]){
            si++;
            pi++;
        }
        else if (next[pi] == -1){
            si++;
        }
        else{
            pi = next[pi];
        }
    }
    return pi == pattern.size() ? si - pi : -1;
}

int main(){
    string s1 = "aksabcafsabcafxdf";
    string s2 = "abcafx";
    int res = getIndext(s1, s2);
    cout << res << endl;
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/inception6-lxc/p/9314904.html