KMP字符串匹配

来源:互联网 发布:itv端口居然能上网 编辑:程序博客网 时间:2024/04/30 00:30
#include <iostream>
#include <string>
using namespace std;
string str,tar;
int f[10000+10];
void Fail () //失败函数
{
    f[0]=-1;               
    for(int j=1;j<str.size();j++)
    {
        int m=f[j-1];     
        while(str.at(m+1)!=str.at(j)&&m>=0)
        m=f[m];
        if(str.at(m+1)==str.at(j))   f[j]=m+1;
        else f[j]=-1;
    }    
}    
int main ()
{
    memset(f,0,sizeof(f));
    cin>>tar>>str;
    int m=0,n=0;
    Fail();
    for(int i=0;i<str.size();i++)
    cout<<f[i]<<endl;
    while(m<tar.size()&&n<str.size())
    {
        if(tar.at(m)==str.at(n))    { m++;   n++; }
        else if(n==0)   m++;
        else n=f[n-1]+1;
    }    
    if(n==str.size())  cout<<m-str.size()<<endl;
    else cout<<-1<<endl;
    system("pause");
    return 0;
}    
原创粉丝点击