一二三四五 上山打老虎

NC18386-字符串

题目链接:https://ac.nowcoder.com/acm/problem/18386

题意:给定一个全是小写字母的字符串S,长度\(\leq10^6\),求最小字串长度,使得这个字串中包括26个小写字母全部。

思路:双指针,l和r,对于每个l,r++找到r合适位置,对于每个r,l++,找到合适位置满足条件,记录字串长度最小值。

坑点:r边界判断容易出错

反思:对于双指针的题目,编码的时候可以采取:遍历l,如果当前r满足条件则r不变,否则r++到刚好满足条件的位置。

#include<iostream>
#include<string>
using namespace std;
string s;
int m[30]={0};
bool check(){
    for(int i=0;i<=25;i++)
        if(m[i]==0)return false;
    return true;
}
int main (){
    cin>>s;
    int len= s.length();
    int l=0,r=0;
    m[s[0]-'a']++;
    while(!check()&&r<=len){
        m[s[++r]-'a']++;
    }
    int ans=r-l+1;
    //cout<<ans<<endl;
    for(;;l++){
        while(!check()){
            r++;
            if(r>=len)break;
            m[s[r]-'a']++;
            }
        if(r>=len)break;
       // cout<<l<<endl;

        ans=min(ans,r-l+1);
        m[s[l]-'a']--;
    }
    cout<<ans<<endl;
    return 0;
}

posted @ 2021-01-21 09:29  黒川川  阅读(81)  评论(0)    收藏  举报