ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Educational Codeforces Round 87 (Rated for Div. 2) B. Ternary String(贪心?蛮好一题)

2020-05-17 20:07:55  阅读:238  来源: 互联网

标签:Educational Rated String ss pos substring int each string


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

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

Input

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

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

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

Output

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

Example Input Copy
7
123
12222133333332
112233
332211
12121212
333333
31121
Output Copy
3
3
4
4
0
0
4
输出最短的同时含有1 2 3这三个数字的子串的长度。
遍历字符串,用三个变量pos[1] pos[2] pos[3]表示在当前位置之前最近一次出现1 2 3的位置(初始化为-1)。每遍历到一个位置先更新对应的pos值,如果此时三个变量都不为-1的话更新答案即可。
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        int pos[4],i;//pos1代表离着当前位置最近的1的位置 其他同理 
        int ans=0x3f3f3f3f;
        pos[1]=pos[2]=pos[3]=-1;
        for(i=0;i<s.size();i++)
        {
            if(i==0)
            {
                pos[s[i]-'0']=0;
                continue;
            }
            int now=s[i]-'0';
            pos[now]=i;
            if(pos[1]!=-1&&pos[2]!=-1&&pos[3]!=-1)
            {
                if(now==1) ans=min(ans,i-min(pos[2],pos[3])+1);
                else if(now==2) ans=min(ans,i-min(pos[1],pos[3])+1);
                else if(now==3) ans=min(ans,i-min(pos[1],pos[2])+1);
            }
        }
        if(ans==0x3f3f3f3f)cout<<0<<endl;
        else cout<<ans<<endl;
    }
    return 0;
}

 



标签:Educational,Rated,String,ss,pos,substring,int,each,string
来源: https://www.cnblogs.com/lipoicyclic/p/12906554.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有