HDOJ3336Count the string-----KMP求前缀串重复次数

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

Problem Description

It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
s: "abab"
The prefixes are: "a", "ab", "aba", "abab"
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6.
The answer may be very large, so output the answer mod 10007.

 

 

Input

The first line is a single integer T, indicating the number of test cases.
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters.

 

 

Output

For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.

 

 

Sample Input

 

1 4 abab

 

 

Sample Output

 

6

题意: 给定字符串s,字符串长度为len,s中共有len个前缀串。

比如给定abab, 则前缀串有a,ab,aba,abab,

求每个前缀串在s中出现次数。

比如对于abab,

a出现2次,

ab出现2次,

aba出现1次,

abab出现1次,

所以共6次。

题解:  

假如某个前缀串在后面重复,比如 abab中前缀串a 在 s[2]出重复,

则对于子串aba,就满足a同时是其前缀和后缀,

这样就容易联想到KMP算法的next数组,

对于假设next[j]表示0-j-1的子串最长相等前后缀的长度,

那next[3] = 1,因为next[3]不等于0,所以以s[0-2]的子串里以s[2]结尾的前缀肯定在末尾处重复了1次。

所以可以算出next数组,for循环遍历一次,如果next[i] != 0,总数就加1,

最后加上len也就是所有前缀串的个数就是答案了。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MOD 10007
char s[200005];
int len;
int Next[200005];

/**
 * 计算next数组
 */
void CalNext() {
   Next[0] = 0;
   Next[1] = 0;
   int k = 0;// 上次计算的next值
   for(int i = 2;i <= len;i++) {
       while(s[i-1] != s[k] && k) {
           k = Next[k];
       }
       if(s[i-1] == s[k]) {
           k++;
       }
       Next[i] = k;
   }
    
}


int main()
{
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%d",&len);
        scanf("%s",s);
        CalNext();
        int count = 0;// 前缀串出现次数
        count = (count+len) % MOD;// 所有前缀串
        for(int i = 1;i <= len;i++) {
            if(Next[i] != 0) {
                count = (count+1) % MOD;
            }
        }
        printf("%d\n",count);
    }
    
    return 0;
} 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值