【CF】---K-Dominant Character(思维)

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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值