http://www.yyycode.cn/index.php/2020/05/17/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 (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.ExampleinputCopy
7 123 12222133333332 112233 332211 12121212 333333 31121
outputCopy
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的。
思路:暴力的话枚举每一个字母,找到满足条件的最短的子串。O(n^2)
O(n^2)的区间问题常用优化有尺取法[双指针].O(n)
有i,j,两个快慢指针,i先走,当走到的位置发现已经有满足有1,2,3,那么这时候再让j往前走,更新长度,当[j,i]这段区间不满足了,那么i再走。就好像一个蛆的扭动
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5;
typedef long long LL;
int main(void)
{
LL t;cin>>t;
while(t--)
{
string str;cin>>str;
LL a=-1;LL b=-1;LL c=-1;
LL sum=0x3f3f3f3f;LL ans=0;
for(LL i=0,j=0;i<str.size();i++)
{
if(str[i]=='1') a=i;
if(str[i]=='2') b=i;
if(str[i]=='3') c=i;
if(a!=-1&&b!=-1&&c!=-1)
{
ans=i-(min(a,min(b,c)))+1;
sum=min(ans,sum);
}
}
if(sum==0x3f3f3f3f)
cout<<0<<endl;
else
cout<<sum<<endl;
}
return 0;
}