题目链接:https://www.hackerrank.com/contests/ieeextreme-challenges/challenges/pattern-3/submissions/code/1301226664
题意:求字符串的最小循环节。
解法:KMP裸题,思想在训练指南P211-P214
//Hacker Rank Pattern 3
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
int f[maxn];
string s;
int main(){
int t;
scanf("%d", &t);
while(t--){
cin >> s;
int n = s.size();
memset(f,0,sizeof(f)); //根据其前一个字母得到
for(int i=1;i<s.size();i++)
{
int j=f[i];
while(j && s[i]!=s[j])
j=f[j];
f[i+1]=(s[i]==s[j])?j+1:0;
}
printf("%d\n", n - f[n]);
}
return 0;
}
本文介绍了一种使用KMP算法求解字符串最小循环节的方法,并提供了完整的C++代码实现。通过预处理字符串的next数组,快速找到最小循环节长度。

被折叠的 条评论
为什么被折叠?



