CF(补题)

B. Ternary String
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input outputstandard output
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
7
123
12222133333332
112233
332211
12121212
333333
31121
Output
3
3
4
4
0
0
4
Note
Consider the example test: In the first test case, the substring 123 can be used. In the second test case, the substring 213 can be used. In the third test case, the substring 1223 can be used. In the fourth test case, the substring 3221 can be used. In the fifth test case, there is no character 3 in ss. In the sixth test case, there is no character 1 in ss. In the seventh test case, the substring 3112 can be used
题意:就是找出字符串中最短连续子字符串得同时包含1,2,3这三个字符;
解题思路:刚开始被思路跑偏了,一直找的是往中间缩短字符串看是否有满足情况的,但是这样却忽略了当头或者尾部就有时的子字符串。
看大佬代码:一下就明了,直接从头部开始找,找符合情况的字符串,然后再取最短的即可;

#include <bits/stdc++.h> 
using namespace std;
#define maxn 400005
int main()
{    
     int t;   
     cin>>t;    
     while(t--)        
     {            
         string s;            
         cin>>s;            
         int l,ans=maxn,one=maxn,t=maxn,th=maxn;
         l=s.size();            
         for(int i=0;i<l;i++)               
          {                    
             if(s[i]=='1') one=i;                    
             if(s[i]=='2') t=i;                    
             if(s[i]=='3') th=i;
             ans=min(ans,max(one,max(t,th))-min(one,min(t,th))+1);                   
          }            
          if(ans>200000) cout<<0<<endl;            
          else cout<<ans<<endl;        
         }    
     return 0;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值