码迷,mamicode.com
首页 > 编程语言 > 详细

KMP算法

时间:2018-07-15 22:17:18      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:tor   pause   using   class   turn   ace   ring   bsp   div   

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

代码如下:

#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;
}

 

KMP算法

标签:tor   pause   using   class   turn   ace   ring   bsp   div   

原文地址:https://www.cnblogs.com/inception6-lxc/p/9314904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!