3624. 三值字符串
#include <bits/stdc++.h>
using namespace std;
const int M = 200005;
int t;
char a[M];
int main() {
scanf("%d", &t);
while (t--) {
int l = 0x7fffffff;
scanf("%s", a + 1);
int len = strlen(a + 1);
int v1 = 0, v2 = 0, v3 = 0;
for (int i = 1; i <= len; ++i) {
if (a[i] == '1') {
v1 = i;
if (v2 && v3)
l = min(l, i - min(v2, v3) + 1);
} else if (a[i] == '2') {
v2 = i;
if (v1 && v3)
l = min(l, i - min(v1, v3) + 1);
} else if (a[i] == '3') {
v3 = i;
if (v1 && v2)
l = min(l, i - min(v1, v2) + 1);
}
}
if (l != 0x7fffffff) {
printf("%d\n", l);
} else {
printf("0\n");
}
}
return 0;
}
//这是yxc老师的
#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int n;
char s[N];
int cnt[3];
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%s", s);
n = strlen(s);
memset(cnt, 0, sizeof cnt);
int res = n + 1;
for (int i = 0, j = 0; i < n; ++i) {
cnt[s[i] - '1']++;
while (cnt[s[j] - '1'] > 1)
cnt[s[j++] - '1']--;
if (cnt[0] && cnt[1] && cnt[2])
res = min(res, i - j + 1);
}
if (res == n + 1)
res = 0;
printf("%d\n", res);
}
return 0;
}
题解:cnt数组记录数字的个数,这里运用了双指针做法,j代表左端点,i代表右端点,做法和求最长不重复子序列相似。