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;
    }

  • 相关阅读:
    CocoaPods 中删除不需要的第三方
    真机测试是提示 的 iPhone is busy: Preparing debugger support for
    关于 Expression is not assignable 错误
    关于查询ios的app更新的历史版本记录
    ios开启双重认证之填坑式教学
    swift 有道 翻译文档(2 条件语句 循环语句)
    swift 有道 翻译文档(1 定义变量常量,数组字典)
    渐变UI
    cornerstone 使用
    cocoaPods安装
  • 原文地址:https://www.cnblogs.com/orangeblog/p/2413938.html
Copyright © 2011-2022 走看看