*HDU 3336 - Count the string(KMP)

题目:

http://acm.hdu.edu.cn/showproblem.php?pid=3336

题意:

求出字符串的前缀在字符串中重复的总次数。

思路:

kmp 的原始next 数组,next[i]表示前i-1个字符中前后匹配的最大长度是next[i].

将前后匹配的串个数相加 + 字符串的长度 即可得到答案。

点击打开链接

AC.

#include <iostream>
#include <cstdio>

using namespace std;
const int mod = 10007;
const int maxn = 2e5+5;
char t[maxn];
int net[maxn];
int n;

void getnext()
{
    int i = 0, j = -1;
    net[0] = -1;
    while(i < n) {
        if(j == -1 || t[i] == t[j]) {
            ++i; ++j;
            net[i] = j;
        }
        else j = net[j];
    }
}

int main()
{
    //freopen("in", "r", stdin);
    int T;
    scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        scanf("%s", t);
        getnext();

        int res = net[n] + n;
        for(int i = 0; i < n; ++i) {
            if(net[i] > 0 && net[i] + 1 != net[i+1]) {
                res = (res + net[i]) % mod;
            }
        }
        printf("%d\n", res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值