zoukankan      html  css  js  c++  java
  • Educational Codeforces Round 87 (Rated for Div. 2) B. Ternary 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 (1t200001≤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;
    }


  • 相关阅读:
    python之jupyter
    python处理图片
    python之图片指纹(唯一性的)
    python之操作elasticsearch7.6.0
    elasticsearch之索引
    elasticsearch
    Nginx 出现 403 Forbidden解决方案
    centos 防火墙命令
    centos nginx常用的命令
    搭建centos nginx环境
  • 原文地址:https://www.cnblogs.com/lipoicyclic/p/12906554.html
Copyright © 2011-2022 走看看