Count the string
题目:
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
分析:
这道题是要求我们求出有每个前缀在这个字符串中出现的次数。
首先每个开头作为首字母的子串都是一个前缀,除此之外求出他们在后面出现的次数即可。那么这个总数就分为两部分:一部分值是这个字符串的长度,因为开头首字符的子串和字符串长度相等;另一部分值可以用一个for循环从头跑到尾每次遇到Next[i]的值不为0时,就说明出现了一次循环,总个数加一,并且一直向前回溯,每回溯一次就说明这个长度的字符串又多出现了一次依旧总个数加一,跑完整个字符串,就求出了以开头首字符的不同字符串在后面出现的次数。
代码:
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int Next[10000005];
string str;
void get_next(){
int len = str.size();
int j = 0, k = -1;
Next[0] = -1;
while(j < len){
if(k == -1 || str[j] == str[k]){
k++;
j++;
Next[j] = k;
}
else
k = Next[k];
}
}
int main(){
int t, n;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
cin >> str;
get_next();
int sum = n;
for(int i = 1; i <= str.size(); i++){
int j = i;
while(Next[j] != 0){
sum++;
j = Next[j];
sum %= 10007;
}
}
cout << sum%10007 << endl;
}
return 0;
}
推荐阅读
-
string '??54' (length=8)用什么函数能转换成int类型的?解决思路
-
PHP中奇妙的String
-
Oracle中DBMS_RANDOM.STRING 的用法
-
mysql found_row()与row_count()实例讲解
-
string 类型约束的问题
-
php中count 多维数组长度统计实现方法_PHP教程
-
switch case语句中能否作用在String,long上
-
php中simplexml_load_string使用实例分享
-
php中mysql_real_escape_string()函数的用法介绍
-
求mysql_real_escape_string()防注入详解