Ternary String【简单版最短覆盖子串】

题目描述:原题链接

You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.

A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) characters from the beginning of s and some (possibly zero) characters from the end of s.

Input
The first line contains one integer t (1≤t≤20000) — the number of test cases.

Each test case consists of one line containing the string s (1≤|s|≤200000). It is guaranteed that each character of s is either 1, 2, or 3.

The sum of lengths of all strings in all test cases does not exceed 200000.

Output
For each test case, print one integer — the length of the shortest contiguous substring of s containing all three types of characters at least once. If there is no such substring, print 0 instead.

Example
input
7
123
12222133333332
112233
332211
12121212
333333
31121
output
3
3
4
4
0
0
4

思路:

遍历每一个长度,当序列中存在1,2,3时,每一个新产生的123序列即为当前长度减去1,2,3中最开始的位置,再取最小即为答案。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int N=200010;


int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        char s[N];
        scanf("%s",s+1);
        int n = strlen(s+1);

        int t[4] = {0,0,0,0};

        int ans = -1;
        for(int i=1; i<=n; ++i)
        {
            t[s[i]-'0'] = i;
            if(!t[1] || !t[2] || !t[3]) continue;

            int len = i - min(t[1], min(t[2],t[3])) + 1;
            if(ans==-1 || ans>len)
                ans = len;
        }

        if(ans == -1) printf("0\n");
        else printf("%d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值