zoukankan      html  css  js  c++  java
  • 模式匹配算法-kmp

    #include<iostream>
    #include<string.h>
    using namespace std;
    #define MAXLEN 255
    //预定义最大串长为255
    typedef struct {
        char ch[MAXLEN];
        int length;
    } SString;
    typedef struct {
        char *ch;
        int length;
    } HString;
    void copy(SString *T,char*s) {
        int length=strlen(s);
        for(int i=0; i<length; i++) {
            (*T).ch[i+1]=s[i];
        }
        (*T).length=length;
    }
    int Index(SString S, SString T) {
        int i=1, j=1;
        while(i<=S.length&&j<=T.length ) {
            if (S.ch[i] ==T.ch [j] ) {
                ++i;
                ++j; //继续比较后继字符
            } else {
                i=i-j+2;
                j=1; //指针后退重新开始匹配
            }
        }
        if(j>T.length)
            return i-T.length;
    
        else return 0;
    }
    
    void get_next(SString T,int next[]) {
        int i=1,j=0;
        next[1]=0;
        while(i<T.length ) {
            if (j==0||T.ch[i]==T.ch[j]) {
                ++i ;
                ++j;
                next[i]=j; //若Pi=Pj ,则next[j+1] =next[j]+1
            } else
                j=next[j]; //否则令j=next[j]循环继续
        }
    }
    int Index_KMP(SString S, SString T, int next[]) {
        int i=1,j=1 ;
        while(i<=S.length&&j<=T.length) {
            if (j==0||S.ch[i]==T.ch [j]) {
                ++i;
                ++j;//继续比较后继字符
            } else
                j=next [j];//模式串向右移动
        }
        if (j>T.length )
            return i-T.length;
        else
            return 0;
    }
    
    void get_nextval(SString T ,int nextval[]) {
        int i=1, j=0;
        nextval[1]=0;
        while (i<T.length ) {
            if (j==0||T.ch [i]==T.ch[j]) {
                ++i,++j;
                if (T.ch[i]!=T.ch[j]) nextval[i]=j ;
                else nextval [i] =nextval[j];
                }
                else
                j=nextval[j];
            }
    }
    int main() {
    
        SString S,T,K;
        char *s1="12345678";
        char *s2="234";
        copy(&S,s1);
        copy(&T,s2);
        char *s3="aabaabaabaac";
        copy(&K,s3);
        
    
        int next_val[13];
    //    get_nextval(K,next_val);
        get_next(K,next_val);
        for(int i=1;i<=12;i++)
        {
            cout<<next_val[i]<<" ";
        }
        cout<<endl;
    cout<<Index_KMP(S, T, next_val);
    //    cout<<    Index(S,T);
        return 0;
    }
  • 相关阅读:
    node 父子进程传递对象
    js 按照字母进行分组
    native react 代码智能提示
    VScode 使用emmet
    c# webapi swagger
    c# 前台和后台线程
    Java——字节和字符的区别
    Java——类的访问修饰符
    Java——面向对象
    Java——内存中的数组
  • 原文地址:https://www.cnblogs.com/tianyudizhua/p/13416384.html
Copyright © 2011-2022 走看看