kmp模式串2求匹配的趟数

来源:互联网 发布:南宁哪里有mac专柜 编辑:程序博客网 时间:2024/06/06 00:49

Description

输入一个主串和一个子串,用KMP进行匹配,问进行几趟匹配才成功,若没成功,则输出0

Input

输入一个主串和一个子串

Output

匹配的趟数

Sample Input

ababcabcacbababcac

Sample Output

3

HINT

Source

#include <iostream>#include<string.h>#include<cstdio>using namespace std;int i,j,len1,len2;int next[101];char s[101],t[101];int main(){    cin>>s;    cin>>t;    len1=strlen(s);//string类用a.length()函数    len2=strlen(t);    int i=0,j=-1;    next[0]=-1;    while(i<len2)//求next值是专门针对子串的(t串)    {        if(j==-1||t[i]==t[j])        {            i++;            j++;            //if(a[i]!=a[j])             //   next[i]=j;           // else                next[i]=j;        }        else            j=next[j];    }//已经算出了next数组    i=0,j=0;    int cnt=1;    bool flag=false;    while(i<len1)//遍历所有的s串    {        if(s[i]==t[j])        {            i++;            j++;            if(t[j]=='\0')//t串到头,flag=1标识            {                flag=true;                break;            }        }          else if(next[j]==-1)          {              j=0;              i++;              cnt++;          }          else//j==-1||t[i]==t[j]排除后          {              j=next[j];              cnt++;          }    }    if(flag)        cout<<cnt<<endl;    else        cout<<"0"<<endl;    return 0;}


 

0 0