hdu 2087 剪花布条(KMP)

题目连接:hdu 2087 剪花布条


题目大意:中文题。。。。


解题思路:KMP,还是找到匹配项的地方入手,让p = 0即可。


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

const int N = 1005;

int n, m, next[N], i;
char T[N], W[N];

void getNext () {
    int p = 0;
    m = strlen(W+1);
    for (i = 2; i <= m; i++) {
        while (p > 0 && W[p+1] != W[i])
            p = next[p];

        if (W[p+1] == W[i])
            p++;

        next[i] = p;
    }
}

int KMP () {
    int ans = 0, p = 0;
    n= strlen(T+1);
    for (i = 1; i <= n; i++) {
        while (p > 0 && W[p+1] != T[i])
            p = next[p];

        if (W[p+1] == T[i])
            p++;

        if (p == m) {
            ans++;
            p = 0;
        }
    }
    return ans;
}

int main () {
    while (scanf("%s", T+1) == 1 && T[1] != '#') {
        scanf("%s", W+1);
        getNext ();
        printf("%d\n", KMP());
    }
    return 0;
}


你可能感兴趣的:(hdu 2087 剪花布条(KMP))