• 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;
    }
    
  • 相关阅读:
    显示多行字符串
    dowhile
    获取系统的相关文件夹
    DLL 实际应用版本
    ShellExecute
    LoadLibrary
    MFC DLL的创建
    在DLL中存放资源
    替换字符串
    RemoveDirectoryB
  • 原文地址:https://www.cnblogs.com/orion7/p/7899926.html
Copyright © 2020-2023  润新知