3624. 三值字符串

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代表右端点,做法和求最长不重复子序列相似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值