剪花布条 - HDU 2087(简单KMP | 暴力)

分析:基础的练习...............

=======================================================================================
#include<stdio.h>
#include<string.h>

const int MAXN = 1e4+7;

void GetNext(char s[], int next[], int N)
{
    int i=0, j=-1;

    while(i<N)
    {
        if(j==-1 || s[i]==s[j])
            next[++i] = ++j;
        else
            j = next[j];
    }
}
int KMP(char a[], char b[])
{
    int i=0, j=0, ans=0, next[MAXN]={-1};
    int Na=strlen(a), Nb=strlen(b);

    GetNext(b, next, Nb);

    while(i < Na)
    {
        while(j==-1 || (a[i]==b[j] && i<Na) )
            i++, j++;

        if(j == Nb)
            j=0, ans++;
        else
            j = next[j];
    }

    return ans;
}

int main()
{
    char a[MAXN], b[MAXN];

    while(scanf("%s", a), strcmp(a, "#"))
    {
        scanf("%s", b);

        printf("%d\n", KMP(a, b));
    }

    return 0;
}

 

posted @ 2015-08-14 15:21  无忧望月  阅读(155)  评论(0编辑  收藏  举报
levels of contents