基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
给出一个字符串,求该字符串的一个子串S,S包含A-Z中的全部字母,并且S是所有符合条件的子串中最短的,输出S的长度。如果给出的字符串中并不包括A-Z中的全部字母,则输出No Solution。
Input
第1行,1个字符串。字符串的长度 <= 100000。
Output
输出包含A-Z的最短子串长度。如果没有符合条件的子串,则输出No Solution。
Input示例
BVCABCDEFFGHIJKLMMNOPQRSTUVWXZYZZ
Output示例
28
思路: 二分 || 贪心 || 尺取法
一,二分:用数组 a[i][30]保存前 i 个字母的 26个字母的个数, 在遍历字符串,对于 前 i 个字符,可二分查找以a[i]为右端点的包含26字母的字符串的左端点。
二,贪心:由二分思路可想到,对于查找以a[i]为右端点的包含26字母的字符串的左端点l。那么只要保存每个字母出现的下标最大值即可,那么 左端点 l 就是 26个字母的下标的最小值。
三,尺取法: 对于贪心思想,每次左端点取 26个字母的下标最小值, 那么可以当找到一个符合条件的字符串时,可以将它的左端点向右移,直到恰好保留26个字母为止,在移动右端点找下一区间,在移动左端点使其恰好保留26个字母,保留字符串的最小长度,这样反复即可。
Code 1:
// 二分 O(nlog(n)*26)
#include<iostream>
using namespace std;
const int MAX_N=100005;
string str;
int a[MAX_N][30];
int main()
{
ios::sync_with_stdio(false);
cin>>str;
for(int i=0;i<str.size();++i)
{
for(int j=0;j<26;++j)
a[i+1][j]=a[i][j];
a[i+1][str[i]-'A']++;
}
int l,r,h,ans=1e9;
for(int i=26;i<=str.size();++i)
{
bool boo=false;
l=1; r=i;
while(l<=r){
h=(l+r)>>1;
int k=0;
while(k<26){
if((!h&&a[i][k]==a[h][k])||(h&&a[i][k]==a[h-1][k])){
break;
}
k++;
}
if(k==26){
l=h+1; boo=true;
}else r=h-1;
}
if(boo==true) ans=min(ans,i-r+1);
}
if(ans!=1e9) cout<<ans<<endl;
else cout<<"No Solution"<<endl;
return 0;
}
Code 2:
// 贪心 O(n*26)
#include<iostream>
using namespace std;
int n;
int a[30];
string str;
int main()
{
ios::sync_with_stdio(false);
cin>>str;
int ans=1e9;
for(int i=0;i<str.size();++i)
{
a[str[i]-'A']=i;
int k=0,l=i;
while(k<26&&a[k]){
l=min(l,a[k]);
k++;
}
if(k==26) ans=min(ans,i-l+1);
}
if(ans!=1e9) cout<<ans<<endl;
else cout<<"No Solution"<<endl;
return 0;
}
Code 3:
//尺取法 O(n)
#include<iostream>
using namespace std;
int a[30];
string str;
int main()
{
ios::sync_with_stdio(false);
cin>>str;
int ans=1e9,sum=0,l=0;
for(int i=0;i<str.size();++i)
{
if(a[str[i]-'A']==0) ++sum;
++a[str[i]-'A'];
while(a[str[l]-'A']>1){
--a[str[l++]-'A'];
}
if(sum==26) ans=min(ans,i-l+1);
}
if(ans!=1e9) cout<<ans<<endl;
else cout<<"No Solution"<<endl;
return 0;
}