• 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;
    }
  • 相关阅读:
    Appium环境配置
    MongoDB_09——执行计划
    mongoDB_08索引的操作
    MongoDB常用命令
    MongoDB_07_复杂查询
    MongoDB_06_分页查询
    docker-ce 安装
    Kubernetes集群搭建 ver1.20.5
    Deploying Portainer CE in Docker
    mysql常用命令
  • 原文地址:https://www.cnblogs.com/inception6-lxc/p/9314904.html
Copyright © 2020-2023  润新知