Codeforces 888C K-Dominant Character 9(思维)

题目描述:


You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.


You have to find minimum k such that there exists at least one k-dominant character.


Input
The first line contains string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 100000).


Output
Print one number — the minimum value of k such that there exists at least one k-dominant character.


Example


Input
abacaba
Output
2
Input
zzzzz
Output
1
Input
abcde
Output

3


题意:给定一字符串s,其长度为k(1<=k<=s)的任意子串里都包含同一字母c,求满足该条件的最小的k


思路:开始想的很复杂。其实对于每个字母,我们只考虑串中和它相同的字母即可。用一个数组储存该字母上一次出现的位置。再用一个数组更新该字母每两个之间距离的最大值。再取所有种类字母的间隔最大值的最小的那个就是答案。

要注意最前面和最末尾都要假定有与当前字母相同的一个字母,如样例3。

比如样例1,abacaba,字母a间隔的最大值是2,b是4,c是4.取里面的最小值为a的2.

对于样例3,因为我们假定最前面和最末尾都有相同的字母,这样对于字母c,串变为cabcdec,求出c的为3,其他为4、5.


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[100005];
int last[26],ans[26],n;
void solve()
{
	memset(last,-1,sizeof(last));
	memset(ans,-1,sizeof(ans));
	n=strlen(s);
	
	int i,j,t;
	for(i=0;i<n;i++)
	{
		t=s[i]-'a';
		if(last[t]==-1)
		{
			last[t]=i;
			ans[t]=max(ans[t],i+1);//假定开头有与当前相同字母
		}
		else
		{
			ans[t]=max(ans[t],i-last[t]);
			last[t]=i;
		}
	}
	for(i=0;i<26;i++)//假定串最后面有与当前相同字母
	{
		if(last[t]!=-1)
		ans[i]=max(ans[i],n-last[i]);
	}
	sort(ans,ans+26);
	for(i=0;i<26;i++)
	if(ans[i]!=-1)
	{
		cout<<ans[i]<<endl;
		break;
	}
}
int main()
{
	while(cin>>s)
	{
		solve();
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值