CodeForces 888C K-Dominant Character(模擬)
阿新 • • 發佈:2017-11-26
exist mini tput eof one blog mina nsis i++
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; }
CodeForces 888C K-Dominant Character(模擬)