hdu 3336 Count the string

题目:

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

算法:

    字符串KMP。好的,先来复习一下在KMP中next数组是怎么求的?next[i]表示在i位置前面的串的前缀和后缀相等的长度。例如:abab:-1 0 0 1;其中b位置处next为1,表示串aba中的前缀a和后缀a相等,长度为1。

    首先,我们规定第一个字符的模式值为-1,若S[j] == S[k],那么就有next[j+1] = next[k+1];若不相等,即前后缀匹配失败,k = next[k]。

思路:

    利用next数组求出每个prefix的匹配串个数。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int t,n;
char s[200020],s1[200020];
int next[200020];

void get_nextval()
{
    int i,j;
    i=-1;
    j=0;
    next[0]=-1;
    while (j<n)
    {
        if(i==-1 || s[i]==s[j])
        {
            j++; i++;
            next[j]=i;
        }
        else
            i=next[i];
     }
}

int main()
{
    //freopen("input.txt","r",stdin);
    int sum,j;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        getchar();
        gets(s);
        get_nextval();
        sum = n;    //一定存在的串个数
        for(int i=1; i<=n; i++)
        {
            for(j=next[i]; j; sum++)
                j = next[j];
            sum %= 10007;
        }
        printf("%d\n",sum);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值