UVA 455 Periodic Strings KMP算法

2 篇文章 0 订阅

题意:

求一个字符串的最小周期。长度不超过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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值