zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    函数 对象 入门总结
    js 禁止复制粘贴全选
    CSS3个人盲点总结【总结中..........】
    was设置事务超时
    阿里前DBA的故事
    转型思考
    自卑
    关于BigDecimal的使用
    少睡与吸烟影响IQ
    DB2中OLAP函数使用示例
  • 原文地址:https://www.cnblogs.com/inception6-lxc/p/9314904.html
Copyright © 2011-2022 走看看