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.
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.
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.
7 123 12222133333332 112233 332211 12121212 333333 31121
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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!