Step1 Problem:
给你字符串s, 求所有前缀,在原串出现次数(可重叠)和。
Step2 Ideas:
个人习惯从0开始,next[0] = 0;
next[i] : 代表下标从 0 到 i 这个子串,后缀 = 前缀 最长长度(不包括自身)。
枚举 i 从 0 到 len-1,对于每个 i 结尾的 所有后缀 = 前缀 的个数都求出来,然后求和。
Step3 Code:
#include<bits/stdc++.h> using namespace std; const int N = 2e5+100; char s[N]; int nex[N]; void get_next() { int len = strlen(s); nex[0] = 0; for(int i = 1; i < len; i++) { int j = nex[i-1]; while(j && s[i] != s[j]) j = nex[j-1]; if(s[i] == s[j]) nex[i] = j+1; else nex[i] = 0; } } int main() { int T, n; scanf("%d", &T); while(T--) { scanf("%d %s", &n, s); get_next(); int ans = n; for(int i = 0; i < n; i++)//枚举i { int t = i; while(nex[t]) {//求所有i结尾 后缀 = 前缀子串个数和 ans++; t = nex[t-1]; } ans %= 10007; } printf("%d\n", ans); } return 0; }