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 \le t \le 200001≤t≤20000) — the number of test cases.
Each test case consists of one line containing the string ss (1 \le |s| \le 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.
题意:
给你一个字符串ss,其中每个字符都是1,2,或3。你必须选择一个最短的连续子串,使其至少包含这三个字符中的每一个。
字符串s的连续子串是指从s的开头去掉一些(可能是零)字符,从s的结尾去掉一些(可能是零)字符,就可以得到一个字符串。
输入
第一行包含一个整数tt(1\le t\le 20000)--测试案例的数量。
每个测试用例由一行包含字符串s (1≤∣s∣≤200000) 。保证ss的每个字符都是1,2,或3。
所有测试案例中的所有字符串的长度之和不超过200000。
目的寻找最短子串包含1,2,3;
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef long long LL;
typedef pair<int,int>PII;
const int N = 4e5+5;
string s;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
cin >> s;
LL l1 = N, l2 = N, l3 = N, ans =N;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '1') l1 = i;
if (s[i] == '2') l2 = i;
if (s[i] == '3') l3 = i;
ans = min(ans, max(l1, max(l2, l3)) - min(l1, min(l2, l3))+1);
}
if (ans>200000) cout << 0 << endl;
else cout << ans << endl;
}
return 0;
}
考虑到若无解,则1,2,3中至少有一个未出现,即l1,l2,l3中至少有一个一直为N,最坏情况下会有2e5个相同字符,此时的ans取得最大值(4e5+5-2e5)为2e5+5,所以当ans大于2e5时此时为无解,考虑到有解情况,每次更新ans变为包含三个字符的最小位置,即用三个位置中的最大值减去最小值+1,即可(r-l+1);