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

原文地址:https://www.cnblogs.com/orangeblog/p/2413938.html