最短的包含字符串

Description

给出一个字符串,求该字符串的一个子串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

代码如下:

#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <ctime>
#define maxn 10007
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define eps 0.00000001
using namespace std;
typedef long long ll;
char a[111111];
int s[500];
int main()
{
    cin>>a;
    int l=strlen(a);
    int i=0,j=0,sum=0,now=INF;
    while(j<l)
    {
        if(sum<26)//判断是否26个字母是否都出现过
        {
            s[a[j]]++;
            if(s[a[j]]==1)
                sum++;
        }
        j++;
        if(sum==26)//当26个字母都出现了,开始缩小范围判断最小范围
        {
           now=min(now,j-i);
           while(sum==26)
           {
               s[a[i]]--;
               if(!s[a[i]])
                    sum--;
               now=min(now,j-i);
               i++;
           }
        }
    }
    if(now==INF)
        cout<<"No Solution"<<endl;
    else
        cout<<now<<endl;
    return 0;
}

 

字符串问题有不同的场景,以下为你介绍两种常见场景及对应的 Python 解决方法: ### 输出字符串字符串的长度 以下是一个 Python 函数,用于找出字符串中各个子字符串长度,它通过将字符串按空格分割成子字符串列表,再找出这些子字符串长度的小值: ```python def find_short(s): # 转换为列表 a = s.split(' ') # 创建一个存放每个子字符串长度数字的列表 len_lis = [] # 存放数字 for i in a: len_lis.append(len(i)) # 使用 min()找出列表中小值 l = min(len_lis) return l print(find_short('weq ert rgyrtht wnkkkk ert 5eg')) ``` ### 找到包含指定字符串所有字符的子串 可以使用滑动窗口算法来解决这个问题,以下是一个示例代码: ```python from collections import Counter def min_window(s, t): target = Counter(t) required = len(target) l, r = 0, 0 formed = 0 window_counts = {} ans = float("inf"), None, None while r < len(s): character = s[r] window_counts[character] = window_counts.get(character, 0) + 1 if character in target and window_counts[character] == target[character]: formed += 1 while l <= r and formed == required: character = s[l] if r - l + 1 < ans[0]: ans = (r - l + 1, l, r) window_counts[character] -= 1 if character in target and window_counts[character] < target[character]: formed -= 1 l += 1 r += 1 return "" if ans[0] == float("inf") else s[ans[1]: ans[2] + 1] S = "ADOBECDDEBANC" T = "ABC" print(min_window(S, T)) ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值