描述
You are given a string?s?such that each its character is either?1,?2, or?3. You have to choose the shortest contiguous substring of?s?such that it contains each of these three characters at least once.
A contiguous substring of string?s?is a string that can be obtained from?s?by removing some (possibly zero) characters from the beginning of?s?and some (possibly zero) characters from the end of?s.
輸入描述
The first line contains one integer?t?(1≤t≤20000) — the number of test cases.
Each test case consists of one line containing the string?s?(1≤∣s∣≤200000). It is guaranteed that each character of?s?is either?1,?2, or?3.
The sum of lengths of all strings in all test cases does not exceed?200000.
輸出描述
For each test case, print one integer — the length of the shortest contiguous substring of?s?containing all three types of characters at least once. If there is no such substring, print?0?instead.
用例輸入 1?
7 123 12222133333332 112233 332211 12121212 333333 31121
用例輸出 1?
3 3 4 4 0 0 4
提示
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?s.
In the sixth test case, there is no character?1?in?s.
In the seventh test case, the substring?3112?can be used.
翻譯:
描述
你會得到一個字符串s這樣,它的每個字符要么是?1、2?還是?3。您必須選擇最短的連續子字符串s這樣它就至少包含這三個字符中的每一個一次。
字符串的連續子字符串s是一個字符串,可以從s通過從開頭刪除一些(可能為零)字符s以及末尾的一些(可能為零)字符s.
輸入描述
第一行包含一個整數t?(1≤噸≤20000) — 測試用例的數量。
每個測試用例都由一行包含字符串s?(1≤∣秒∣≤20000 0).保證每個字符s是?1、2?或?3。
所有測試用例中所有字符串的長度總和不超過20000 0.
輸出描述
對于每個測試用例,打印一個整數 — 最短連續子字符串的長度s至少包含一次所有三種類型的字符。如果沒有這樣的子字符串,請打印0相反。
用例輸入 1?
7
123
12222133333332
112233
332211
12121212
333333
31121
用例輸出 1?
3
3
4
4
0
0
4
提示
請看示例測試:
在第一個測試用例中,可以使用子字符串?123。
在第二個測試用例中,可以使用子字符串213。
在第三個測試用例中,可以使用子字符串?1223。
在第四個測試用例中,可以使用子字符串?3221。
在第五個測試用例中,沒有字符?3s.
在第六個測試用例中,沒有字符?1s.
在第七個測試用例中,可以使用子字符串?3112。
解題思路:
1,將數字存儲到string中
2,寫出函數判斷是否存在123這3個數,如果不存在直接輸出0
3,循環出字符串>3的所有可能并用2的函數判斷,然后比較迭代最小字符數
c++代碼如下:
#include <bits/stdc++.h>using namespace std;bool is_ok(string s)
{int a = 0,b = 0,c = 0;for(int i = 0;i < s.size();++i){char cc = s[i];if(cc == '1') ++a;if(cc == '2') ++b;if(cc == '3') ++c;if(a > 0 && b > 0 && c > 0){return true;}}return false;
}int main()
{int n;cin >> n;while(n--){bool b = false;int res = 20005;string s;cin >> s;for(int i = 0;i <= s.size()-3;++i){for(int j = 3;j <= s.size()-i;++j){string new_s = s.substr(i,j);if(is_ok(new_s)){b = true;res = new_s.size();break;}}}if(b){cout << res << endl;}else{cout << 0 << endl;}}
}