zoukankan      html  css  js  c++  java
  • CodeForces 888C 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的子串包含有相同的字母。

    题解:

    从a到z找一遍就好了,寻找同一字母在序列中出现的最大的间隔,最后取间隔最小的字母。

    自己写的虽然过了,感觉代码写的很烂。

    #include<iostream>
    #include<cstring>
    #include<string>
    using namespace std;
    int main()
    {
        string s;
        while(cin>>s)
        {
            int last[26];
            int a[26]={0},len=s.length();
            memset(last,-1,sizeof(last));
            for(int i=0;i<len;i++)
            {
                int t=s[i]-'a';
                if(last[t]==-1)
                {
                    a[t]=i+1;
                    last[t]=i;
                }
                else
                {
                    a[t]=max(a[t],i-last[t]);
                    last[t]=i;
                }
            }
            int ans=100000;
            for(int i=0;i<26;i++)//处理到字符串结尾的间隔
            {           
                if(last[i]!=-1)
                {
                    a[i]=max(a[i],len-last[i]);
                    ans=min(ans,a[i]);
                }
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    

    参考别人重新写的

    #include<iostream>
    #include<string>
    #include<algorithm>
    using namespace std;
    int main()
    {
        string s;
        while(cin>>s)
        {
            int ans=1e6;
            for(int i='a';i<='z';i++)
            {
                int t=0,k=0;
                for(int j=0;j<s.length();j++)
                {
                    if(s[j]==i)
                        t=0;
                    else
                        t++;
                    k=max(k,t);
                }
                ans=min(ans,k);
            }
            cout<<ans+1<<endl;
        }
        return 0;
    }
    
  • 相关阅读:
    C语言归并排序
    三重for循环实现对二维数组的按列排序(JavaScript)
    MySQL创建子视图并查看的时候,字符集报错问题
    Windows下配置lua环境
    《机器学习》周志华西瓜书读书笔记
    《消费金融真经》读书笔记
    北海之行-小纪
    2017中国资产管理行业发展报告——思维导图
    工作小纪
    全球化3.0:世界是红的 (转载)
  • 原文地址:https://www.cnblogs.com/orion7/p/7899926.html
Copyright © 2011-2022 走看看