time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard 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
Copy
7 123 12222133333332 112233 332211 12121212 333333 31121
output
Copy
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
#include
#include
#include
#include
#include
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
string s;
cin >> s;
int ans = s.size() + 1;
int k[4];
k[3] = k[1] = k[2] = 0;
for (int i = 0; i