1.4-ssssssss

该博客讨论了一个编程问题,要求找到一个包含1, 2, 3三种字符的最短连续子串。给定一个字符串,算法需在O(n)时间内找到满足条件的子串,如果不存在则输出0。代码实现中通过维护三个字符的最早出现位置,并不断更新最短子串长度。
摘要由CSDN通过智能技术生成

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 \le t \le 200001≤t≤20000) — the number of test cases.

Each test case consists of one line containing the string ss (1 \le |s| \le 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.

题意:

给你一个字符串ss,其中每个字符都是1,2,或3。你必须选择一个最短的连续子串,使其至少包含这三个字符中的每一个。

字符串s的连续子串是指从s的开头去掉一些(可能是零)字符,从s的结尾去掉一些(可能是零)字符,就可以得到一个字符串。

输入
第一行包含一个整数tt(1\le t\le 20000)--测试案例的数量。

每个测试用例由一行包含字符串s (1≤∣s∣≤200000) 。保证ss的每个字符都是1,2,或3。

所有测试案例中的所有字符串的长度之和不超过200000。

目的寻找最短子串包含1,2,3;

#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef long long LL;
typedef pair<int,int>PII;
const int N = 4e5+5;
string s;
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t--)
	{
		cin >> s;
		LL l1 = N, l2 = N, l3 = N, ans =N;
		for (int i = 0; i < s.size(); i++)
		{
			if (s[i] == '1') l1 = i;
			if (s[i] == '2') l2 = i;
			if (s[i] == '3') l3 = i;
			ans = min(ans, max(l1, max(l2, l3)) - min(l1, min(l2, l3))+1);
		}
		if (ans>200000) cout << 0 << endl;
		else cout << ans << endl;
	}
	return 0;
}

考虑到若无解,则1,2,3中至少有一个未出现,即l1,l2,l3中至少有一个一直为N,最坏情况下会有2e5个相同字符,此时的ans取得最大值(4e5+5-2e5)为2e5+5,所以当ans大于2e5时此时为无解,考虑到有解情况,每次更新ans变为包含三个字符的最小位置,即用三个位置中的最大值减去最小值+1,即可(r-l+1);
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值