zoukankan      html  css  js  c++  java
  • KMP模式匹配-模板

    KMP模式匹配-模板

    #include<iostream>
    #include<algorithm>
    #include<string>
    #include<cstring>
    #include<vector>
    #include<stack>
    #include<queue>
    using namespace std;
    //模板中的字符串都是用T[0]存储长度
    
    //优化后的next计算数组
    void get_nextval(char* T,int* nextval){
        int i=1,j=0;
        nextval[1]=0;
        while(i<T[0]){
            if(j==0 || T[i]==T[j]){
                ++i;++j;
                if(T[i]!=T[j]){
                    nextval[i] = j;
                }else{
                    nextval[i] = nextval[j];
                }
            }else{
                j = nextval[j];
            }
        }
    }
    
    //未优化的next计算数组
    void get_next(char* T,int* next){
        int i=1,j=0;
        next[1]=0;
        while(i<T[0]){
            if(j==0 || T[i]==T[j]){
                ++i;++j;
                next[i]=j;
            }else{
                j = next[j];
            }
        }
    }
    
    //用T串从S串的pos位置开始进行匹配
    int Index_KMP(char* S,char* T,int pos){
        int i = pos;
        int j = 1;
        int* next = new int[strlen(T) + 1];
        //get_next(T,next);//非优化版本
        get_nextval(T,next);//优化版本
        while(i<=S[0] && j<=T[0]){
            if(j==0 || S[i]==T[j]){
                ++i;++j;
            }else{
                j = next[j];
            }
        }
        delete[] next;
        if(j>T[0])return i-T[0];
        return 0;//匹配失败
    }
    
    //默认从S串的开头进行匹配的KMP函数
    int KMP(char* S,char* T){
        return Index_KMP(S,T,1);
    }
    
    int main(){
        char aim[] = "&sasdffds";
        char bim[] = "&asdf";
        aim[0] = strlen(aim) - 1;
        bim[0] = strlen(bim) - 1;
        cout<< KMP(aim,bim) <<endl;
        return 0;
    }
    
    

    优化后直接使用

    //优化后的next计算数组
    void get_next(char* T,int* next){
        int i=1,j=0;
        next[1]=0;
        while(i<T[0]){
            if(j==0 || T[i]==T[j]){
                i++;j++;
                next[i] = (T[i]==T[j])? next[j] : j;
            }else{
                j = next[j];
            }
        }
    }
    
    //用T串从S串的pos位置开始进行匹配
    int KMP(char* S,char* T,int pos){
        int i = pos;
        int j = 1;
        int* next = new int[strlen(T) + 1];
        get_next(T,next);//优化版本
        while(i<=S[0] && j<=T[0]){
            if(j==0 || S[i]==T[j]){
                i++;j++;
            }else{
                j = next[j];
            }
        }
        delete[] next;
        if(j>T[0])return i-T[0];
        return 0;//匹配失败
    }
    

    OK

  • 相关阅读:
    秋招结束了
    面向萌新的日麻面麻规则简化/改进
    DataTable 转换为Tree 树状结构
    jmeter beanshell断言
    jmeter请求参数包含中文
    Centos7 yum缓存rpm安装包
    nginx针对某个url限制ip访问,常用于后台访问限制
    有关json-lib2.4在转java对象时超过7位数的Double类型会出现科学计数法和精度丢失的问题
    SAP 下载安装
    android okhttp + retrofit使用
  • 原文地址:https://www.cnblogs.com/savennist/p/13756664.html
Copyright © 2011-2022 走看看