K-Dominant Character
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
分析:
题目不是很好理解,意思就是说找到一个最小的数字k,使得主串中任意k长度的子串中都含有至少一个相同的字符。
思路也不是很简单呢,百度了一下才恍然大悟。
关键是找相同字母。
用一个数组记录下每一个字母上次出现的位置,即相邻的相同字母的位置,并且用另一个数组找到每一个字母与相邻相同字母,即两个相邻的相同字母之间的最大距离,并从这些最大距离中找到最小的一个,就是题目所求。
需要注意的是,字符串开头和末尾两个‘空’位置,这两个字符相同,是和当前所研究位置的字符相同的字符。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char str[100000+11];
int dis[26];
int last[26];
int main()
{
while(~scanf("%s",str))
{
memset(dis,-1,sizeof(dis));
memset(last,-1,sizeof(last));//和最开头的‘空’字符之间建立关系
int len=strlen(str);
int i;
for(i=0;i<len;i++)
{
int k=str[i]-'a';
dis[k]=max(dis[k],i-last[k]);
last[k]=i;
}
for(i=0;i<26;i++) //和最末尾的‘空’字符之间建立关系
dis[i]=max(dis[i],len-last[i]);
int ans=len;
for(i=0;i<26;i++)
ans=min(ans,dis[i]);
printf("%d\n",ans);
}
return 0;
}