HDU 2087 剪花布条(水·KMP)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087

解题思路:正常KMP匹配,

在匹配之后让j指向0,因为这一段减掉了,不能在使用这里的一部分了

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 4e5 + 5;

char s[N],str[N];
int fail[N];

void kmp()
{
    int tot = 0;
    int len = strlen(s);
    fail[0] = -1;
    for (int i=0,j=-1;i<len;){
        if (j==-1||s[i]==s[j]){
            i++;j++;
            fail[i] = j;
        }
        else j = fail[j];
    }
    int cnt = 0;
    for (int i=0,j=0;str[i];){
        if (j==-1||str[i]==s[j]){
            i++;j++;
        }
        else j = fail[j];

        if (j==len){
            cnt++;
            j=0;///东西都在这儿
        }
    }
    printf("%d\n",cnt);
}

int main()
{
    while (~scanf("%s",str)&& str[0]!='#'){
        scanf("%s",s);
        kmp();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43768644/article/details/94355903