分析:
用尺取法来做这道题,有点类似双指针算法,两个指针i,j之间维护的区间内恰好满足每个最短的26字母,每次有新字符读入时,若该字符未出现过,则标记数res++,若res==26,则记录下区间长度,比较选取最短的区间长度,时间复杂度为
O
(
n
)
。
O(n)。
O(n)。
代码如下:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;
string str;
int q[200];
int main()
{
int res=1e9;
int ant=0;
cin>>str;
int l=(int)str.length();
for(int i=0,j=0;i<l;i++)
{
if(!q[str[i]]) ant++;
q[str[i]]++;
while(q[str[j]]>1)
{
q[str[j]]--;
j++;
}
if(ant==26) res=min(res,i-j+1);
}
printf("%d\n",res);
return 0;
}