题意:
求一个字符串的最小周期。长度不超过80。
解法:
令test case的最大值是k。
方法一:使用for循环比较字符元素。该方法适应性强,时间复杂度O(kn^2)
方法二:使用kmp算法求next数组。时间复杂度O(kn)
但是使用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;
}