最短的包含字符串

给出一个字符串,求该字符串的一个子串s,s包含A-Z中的全部字母,并且s是所有符合条件的子串中最短的,输出s的长度。如果给出的字符串中并不包括A-Z中的全部字母,则输出No Solution。

 

Input第1行,1个字符串。字符串的长度 <= 100000。Output输出包含A-Z的最短子串s的长度。如果没有符合条件的子串,则输出No Solution。Sample Input

BVCABCDEFFGHIJKLMMNOPQRSTUVWXZYZZ

Sample Output

28


双指针法的灵活运用:
不满足条件时,右指针向右移一步,右指针指向末尾时结束(即无法再增加数时)
满足条件时,更新ans,左指针向右移一步
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;

int main()
{
    int nstr,q=0,p=0,len=0,ans=INF,lnum=0;
    char a[200000]= {0};
    char c;
    int ha[500]= {0};
    gets(a);
    nstr=strlen(a);
    while(1)
    {
        if(lnum<26)
        {
            if(p<nstr)
            {
                c=a[p++];
                if(ha[c]==0)
                    lnum++;
                ha[c]++;
                len++;
            }
            else
                break;
        }
        else if(lnum>=26)
        {
            if(len<ans)
                ans=len;
            c=a[q++];
            if(ha[c]==1)
                lnum--;
            ha[c]--;
            len--;
        }
    }
    if(ans==INF)
        printf("No Solution\n");
    else
        printf("%d\n",ans);
    return 0;
}

 

posted @ 2018-07-17 22:39  Termin  阅读(615)  评论(0编辑  收藏  举报