KMP

来源:互联网 发布:幼儿园手指算法 编辑:程序博客网 时间:2024/06/07 09:12
求子串
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    char a[1020], b[1020];
    int i, j, next[1020], n, m;
    while(scanf("%s",a+1)!= EOF&&a[1]!='#')
    {
        scanf("%s", b+1);
        m=strlen(a+1);
        n=strlen(b+1);
        next[0]=0;
        j=0;i=1;
        while(i<=n)//对模拟串b求next[]
        {
            if(j==0||b[i]==b[j])
            {
                j++;i++;
                next[i]=j;
            }
            else j=next[j];
        }
        i=j=1;
        int cout=0;


        while(i<=m)//KMP
        {
            if(j==0||a[i]==b[j])
            {
                i++;j++;
            }
            else j=next[j];
            if(j>n)
            {
                cout++;

                j=next[j];//重复子串

         //    j=1;//不重复子串

            }
        }
        printf("%d\n", cout);
    }
    return 0;
}
0 0
原创粉丝点击