包含全部字母的最小字串(双指针)

链接:https://ac.nowcoder.com/acm/contest/79240/C
来源:牛客网

给出一个字符串ss仅由小写字母组成,求s中包含所有个小写字母的最小子串长度。

输入描述:
一行一个字符串S。只包含小写字母。S 的长度不超过\(10^6\).

输出描述:
一行一个数字,代表字符串 S 的所有优美子串的最短长度。数据保证存在一个合法的 S 的子串。

示例1
输入
ykjygvedtysvyymzfizzwkjamefxjnrnphqwnfhrnbhwjhqcgqnplodeestu
输出
49

示例2
输入
asdgfhjjagsdghfhjkljklhlkzxmnbzxcmnbvqweyutryewiuortypouyuip
输出
46

这个题一眼双指针,如果不会双指针的可以看看这个我一个学长的公众号
https://mp.weixin.qq.com/s/2Ai1aG2hjy4fyAPzflwU8w

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1e6+100;
typedef long long ll;
char a[maxn];
int len;
int cnt[maxn];
int main(){
	scanf("%s",a+1);
	len=strlen(a+1);
	int ans=len,s=0;
	int l=1;
	for(int r=1;r<=len;r++){
		if(cnt[a[r]-'a']==0){
			s++;
		}
		cnt[a[r]-'a']++;
		while(s==26){
			ans=min(ans,r-l+1);
			if(cnt[a[l]-'a']==1){
				s--;
			}
			cnt[a[l]-'a']--;
			l++;
		}
	}
	cout<<ans<<endl;
}
posted @ 2024-04-08 10:11  lipu123  阅读(35)  评论(0)    收藏  举报