zoukankan      html  css  js  c++  java
  • KMP匹配算法中的失效函数

    今天总算是看懂了字符串匹配算法中的KMP,记下来吧,以后查的时候方便
    失效函数:设模式 P=p0p1....pm-2pm-1, 则它的失效函数定义如下:
    f(j)=k |当 0<=k<j 时,且使得 p0p1....pk=pj-kpj-k+1...pj 的最大数
    f(j)= -1 | 其它情况。
    j 0 1 2 3 4 5 6 7
    p a b a a b c a c
    f(j) -1 -1 0 0 1 -1 0 -1
    详细的不记了,把算法记下来。
    void String::fail{
        
    int lengthP=curLen;
        f[
    0]=-1;
        
    for(int j=1;j<lengthP;j++){
            
    int i=f[j-1];
            
    while(*(ch+j)!=*(ch+i+1)&&i>=0) i=f[i] ;  //递推计算
            if(*(ch+j)==*(ch+i+1))f[j]=i+1;  
            elsef[j]
    =-1;
        }

    }
    下面是普通的匹配算法:
    int String::find(String &pat) const{
        
    char*p=pat.ch; *s=ch; int i=0;
        
    if(*&& *s)
            
    while(i<=curLen-pat.curLen)
                
    if(*p++==*s++){   // C++的精典之处
                    if(!*p) return i;
                }

                
    else { i++; s=ch+i; p=pat.ch; }
        
    return -1;
    }
    下面是 KMP 算法:
    int String::fastFind(String &pat) const {
        
    int posP=0 , pasT=0 ;
        
    int lengthP=pat.curLen, lengthT=curLen;
        
    while(posP<lengthP && posT< lengthT)
            
    if(pat.ch[pasP]==ch[posT]{
                posP
    ++; posT++ ;
            }

            
    else if (posP==0) posT++ ;
            
    else posP=pat.f[posP-1+ 1 ;
        
    if(posP<lengthP) return -1 ;
        
    else return posT-lengthP;
    }
  • 相关阅读:
    flask helloworld
    (16)centos7 日志文件
    (15)centos7 系统服务
    (14)centos7 进程管理
    (13)centos7 任务计划
    (12)centos7 环境变量配置
    [BZOJ2045]双亲数(莫比乌斯反演)
    bzoj2018 [Usaco2009 Nov]农场技艺大赛
    bzoj 1001 [BeiJing2006]狼抓兔子
    bzoj 5056: OI游戏 最短路树的计数
  • 原文地址:https://www.cnblogs.com/icehong/p/46613.html
Copyright © 2011-2022 走看看