hud3336 kmp之对next数组的利用

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

题意:给一串字符串,问这串字符串所有的前缀总共在这个字符串中出现了几次。
举个例子:字符串abab。a出现了2次,ab出现了2次,aba1次,abab1次,总共6次。
准备工作 : 解这道题就要对kmp算法中的next[] 数组有着深刻的理解,如字符串str的next[i] = j。就代表 str中j-i+1这个字符串和0-j这个字符串相等
解题思路 : 将字符串所有的前缀0-i在i+1-n出现的次数相加得到 sum, sum再加上n就是了(共有n个字符串)。

#include <stdio.h>
#include <string.h>
#define N 200000+100
void nextMake(const char *p,int *next);
void kmp(const char *T,const char *p,int *next);
char str1[N],str2[N];
int sum,next[N],dp[N];
int main()
{
    int t,n,i,j;
    scanf("%d",&t);
    while(t--)
    {
       sum = 0;
       scanf("%d %s",&n,str1);
       nextMake(str1,next);
       n = strlen(str1);
       for(i=0; i<n; i++)
       {
        /*比如str=abab这个字符串,next[3] = 2,不就是就表示与
         缀在str[i-n-1]找到了一个匹配吗,所以sum += 1*/ 
           if(next[i] != 0)
               sum = (sum+1)%10007;
       }
       printf("%d\n",(sum+n)%10007);
    }

    return 0;
}
void nextMake(const char *p,int *next)
{
    int k,q;
    int m = strlen(p);
    next[0] = 0;
    for(q=1,k=0; q<m; q++)
    {
        while(k>0 && p[q]!=p[k])
            k = next[k-1];
        if(p[k] == p[q])
        {
            k++;
        }
        next[q] = k;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值