zoukankan      html  css  js  c++  java
  • KMP(模式匹配)

            字符串匹配中的一种KMP,该算法的关键是求出next[],当然理解是必须的,期待更深入的了解;

             hdu2087代码:

    #include<iostream>
    #include<string>
    using namespace std;
    const int Max=1001;
    string str,tar;
    int next[Max];//next串有很多变通的用法,例如hdu1358就是利用next来求重复前缀;

    ////////////////////////////////////////////////////////////////////////////////////////////
    void B_next(int n)
    {
     next[0]=-1;                                                   
     int i=0, j=-1;  //其实这时在某种程度可以把j看成一个模式串的小标(这里的模式串是tar,而母串却在变动)                                                              
     while(i<n)
     {
            if(j==-1||tar[i]==tar[j])//如果二者相等,说明next[i]比next[j]大一
      {

              i++;j++;
             next[i]=j;/////////////而不是next[i-1]+1;
      }
      else
       j=next[j];//不相等时,这时把可以把j看成模式匹配中模式串的下标;
     }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    int main()
    {
     while(cin>>str)
     {
      int count=0;
      if(str[0]=='#')
       break;
      cin>>tar;
      int len1=str.length();
      int len2=tar.length();
      B_next(len2);//建立next[]数组
         int i=0,j=0;
    ///////////////////////////////////////////////////////////////////////////////////////////////////  

    while(i<len1)
      {
       if(j==-1||str[i]==tar[j])     
       {
        j++;i++;
       }
       else
       {
        j=next[j];//不相等时来移动模式串的下标
       }
       if(j>=len2){count++;j=0;}

    ///////////////////////////////////////////////////////////////////////////////////////////////////
      }
      cout<<count<<endl;

     }
    return 0;
    }

  • 相关阅读:
    VS.NET 生成后事件
    SysVinit
    技巧:Linux I/O重定向的一些小技巧
    Ofono/Phonesim 安装和启动
    Memory Hierarchy
    Linux 技巧:让进程在后台可靠运行的几种方法 用 cron 和 at 调度作业 使用 screen 管理你的远程会话
    M. Tim Jones
    How do I install Oracle Java JDK 7?
    详谈 UNIX 环境进程异常退出
    Linux 内核剖析
  • 原文地址:https://www.cnblogs.com/orangeblog/p/2413938.html
Copyright © 2011-2022 走看看