链接:
https://codeforces.com/problemset/problem/1354/B
题意
给你一个有1,2,3组成的字符串,问你能同时含有1,2,3的连续子串最短长度是多少?
多组案例1 ≤ t ≤ 20000
字符串长度1 ≤ |s| ≤ 200000
Example
input
7
123
12222133333332
112233
332211
12121212
333333
31121
output
3
3
4
4
0
0
4
解析
这题数据是2e5,如果套两重循环会超时,所以可以考虑用双指针来做,用i先来遍历,j根据条件开始遍历,i,j都具有单调性;i先遍历字符串,在1,2,3都出现的条件下,j开始遍历直到j到i里1,2,3没有都出现为止,并在这个过程中不断更新满足题意的长度。
#include <iostream>
#include <string>
using namespace std;
const int N = 200010;
int main()
{
int _;
cin >> _;
while (_--)
{
string s;
cin >> s;
int cnt_1 = 0, cnt_2 = 0, cnt_3 = 0;
int min_length = N;
for (int i = 0, j = 0; i < s.size(); i++)
{
if (s[i] == '1') cnt_1++;
if (s[i] == '2') cnt_2++;
if (s[i] == '3') cnt_3++;
while (j < i && cnt_1 && cnt_2 && cnt_3)
{
int t = i - j + 1;
min_length = min(min_length, t);
//cout << t << endl;
if (s[j] == '1') cnt_1--;
if (s[j] == '2') cnt_2--;
if (s[j] == '3') cnt_3--;
j++;
}
}
if (min_length == N) cout << 0 << endl;
else cout << min_length << endl;
}
return 0;
}