B. Ternary String(贪心)

87 篇文章 1 订阅
16 篇文章 1 订阅

题意描述

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.

思路

由于题目规定的子串是删除头或者删除尾的,所以我们先统计每个数字出现的次数,如果一个数字重复出现,就开始从头删去,最后当1、2、3都出现时,就统计最小出现次数即可

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1e5+10;
const int M=1e6;
const int INF=0x3f3f3f3f;
const int MOD=1000000007;
int a[N];
string str[6]={"123","132","213","231","312","321"};
int ans=INF;
int main()
{
    IOS;
    int T;cin>>T;
    while(T--){
        int cnt[4];
        memset(cnt,0,sizeof cnt);
        string s;cin>>s;
        ans=INF;
        int l=0;
        for(int i=0;i<s.size();i++){
            cnt[s[i]-'0']++;
            while(cnt[s[l]-'0']>=2){
                cnt[s[l]-'0']--;
                l++;
            }
            if(cnt[1] && cnt[3] && cnt[2]) ans=min(ans,i-l+1);
        }
        if(ans==INF) cout<<0<<endl;
        else cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值