网址:https://vjudge.net/problem/UVA-455
题意:
求一个字符串的最小周期。长度不超过$80$。
解法:
使用$kmp$算法,如果存在$abcda$串,$n-next[n]$将输出$4$,实际结果是$5$。这个错误结果的产生是因为字符串的后缀子串与前缀子串一致。导致错误。
所以只能通过判断是否是完全周期串,如果不是,输出串的长度。
AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
int nexts[100];
string str;
void getnext(string &str)
{
memset(nexts, 0, sizeof(nexts));
nexts[0] = -1;
int k = 0, j = -1;
while (k < str.size())
{
if (j == -1 || str[j] == str[k])
nexts[++k] = ++j;
else
j = nexts[j];
}
}
int main()
{
ios::sync_with_stdio(0);
int n;
cin >> n;
while (n--)
{
cin >> str;
getnext(str);
int k;
if (str.size() % (str.size() - nexts[str.size()]) == 0)
k = str.size() - nexts[str.size()];
else
k = str.size();
if (n > 0)
cout << k << endl << endl;
else
cout << k << endl;
}
return 0;
}