1.输入重复序列的字符串,如果周期不存在,输出NO,如果周期存在,输出最小周期。
2.代码:
# include <iostream>
# include <string>
using namespace std;
int MinPeriod(char *p)
{
int len = (int)strlen(p);
if (len == 0)
return -1;
int *next = new int[len];
next[0] = -1;
int k = -1;
int j = 0;
while (j < len - 1)
{
if ((k == -1) || (p[j + 1] == p[k]))
{
++k;
++j;
next[j] = k;
//cout << j << ':' << next[j] << endl;
}
else
k = next[k];
}
int last = next[len - 1];
delete[] next;
if (len % (len - last) == 0)
return len - last;
return -1;
return 0;
}
int main()
{
char str[] = { "abcabcabcabc" };
int min = MinPeriod(str);
if (min == -1)
{
cout << "NO" << endl;
}
else
cout << "YES! 字符串的最小周期为:" << min << endl;
}
3.结果:
YES! 字符串的最小周期为:3
请按任意键继续. . .