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

给出一个字符串,求该字符串的一个子串S,S包含A-Z中的全部字母,并且S是所有符合条件的子串中最短的,输出S的长度。如果给出的字符串中并不包括A-Z中的全部字母,则输出No Solution。
Input
第1行,1个字符串。字符串的长度 <= 100000。
Output
输出包含A-Z的最短子串长度。如果没有符合条件的子串,则输出No Solution。
Input示例
BVCABCDEFFGHIJKLMMNOPQRSTUVWXZYZZ
Output示例
28

#include<iostream>
#include<string>
using namespace std;
int ch[26];
bool ok()
{
    for(int i=0;i<26;i++)
    {
        if(ch[i]==0)return false;
    }
    return true;
}
int main()
{
    string s;
    cin>>s;
    int len=s.size();
    int ans=100005;
    int l=0;int r=25;
    for(int i=l;i<=r;i++){int t=s[i]-'A';ch[t]++;}
    while(l<=len-26&&r<len)
    {
        while(!ok()&&r<len-1)
        {
            ch[s[++r]-'A']++;
        }
        if(ok()){ans=min(ans,r-l+1);}
        ch[s[l]-'A']--;
        l++;
    }
    if(ans!=100005)
    cout<<ans<<endl;
    else cout<<"No Solution"<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/linruier/p/9485180.html