51NOD--1127 最短的包含字符串--尺取法

1127 最短的包含字符串

  1. 1 秒
  2.  
  3. 131,072 KB
  4.  
  5. 20 分
  6.  
  7. 3 级题

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

 收起

输入

第1行,1个字符串。字符串的长度 <= 100000。

输出

输出包含A-Z的最短子串s的长度。如果没有符合条件的子串,则输出No Solution。

输入样例

BVCABCDEFFGHIJKLMMNOPQRSTUVWXZYZZ

输出样例

28

怎么找这个最短序列是关键。当包含了26个英文字母的时候,让左指针转移,此时需要判断。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=100000+66;
const ll mod=1e9+7;
char s[maxn];
int a[1000];
int main()
{
    cin>>s;
    //cout<<len<<endl;
    int l=0;
    int t=0;
    int ans=0x3f3f3f3f;
    int flag=0;
    memset(a,0,sizeof(a));
    for(int i=0; s[i]; i++)
    {
        //cout<<s[i]<<"  ";
        if(a[s[i]]==0)
        {
            t++;
            // cout<<s[i]<<"--";
        }
        //cout<<t<<endl;
        a[s[i]]++;
        while(a[s[l]]>1)
        {
            a[s[l]]--;
            l++;
        }
        if(t==26)
            ans=min(ans,i-l+1);
        //cout<<ans<<endl;
    }
    if(ans!=0x3f3f3f3f)
        printf("%d\n",ans);
    else
        printf("No Solution\n");
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CeShi
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string str;
            str=Console.ReadLine();
            //Console.WriteLine(str);
            int len = str.Length;
            //Console.WriteLine(len);
            int []num=new int[1000];//
            int t = 0;
            Boolean flag = false;
            int l = 0;
            int ans = 99999999;
            for(int i=0;i<len;i++)
                num[i]=0;
            for(int i=0;i<len;i++)
            {
                if(num[str[i]]==0)
                {
                    t++;//包含了多少字母呢
                }
                num[str[i]]++;
                while (t==26)
                {
                    flag = true;
                    ans = Math.Min(ans, i - l + 1);
                    num[str[l]]--;//让左指针不断移动
                    if (num[str[l]] == 0)
                        t--;//---
                    l++;
                    //目的是让l不断左移!
                }
            }
            if(!flag)
            {
                Console.WriteLine("No Solution");
            }else
            {
                Console.WriteLine(ans);
            }

        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值