51Nod1127 最短的包含字符串(尺取法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42391248/article/details/85224517

尺取法:由两个指针l,r移动维护,l到r为符合要求的长度,不断移动l和r,直到r到头为止。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
using namespace std;
const int INF=1e9+7;
int main()
{
	string s;
	cin>>s;
	int l=0,r=0,t[26]={0},sum=0,ans=INF;
	for(;r<s.length();r++)
	{
		if(t[s[r]-'A']==0) sum++;		
		t[s[r]-'A']++;
		//移动l,移动规则为:如果字母s[l]的前面还有这个字母,就向前移动l
		while(t[s[l]-'A']>1) t[s[l++]-'A']--;	
		//记录最小的长度 		
		if(sum==26) ans=min(ans,r-l+1);
	}
	if(ans==INF) cout<<"No Solution"<<endl;
	else cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42391248/article/details/85224517