B. Ternary String(贪心)
题意描述
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.
Input 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.
Output 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、2、3都出现时,就统计最小出现次数即可
AC代码
#include<bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1e5+10;
const int M=1e6;
const int INF=0x3f3f3f3f;
const int MOD=1000000007;
int a[N];
string str[6]={"123","132","213","231","312","321"};
int ans=INF;
int main()
{
IOS;
int T;cin>>T;
while(T--){
int cnt[4];
memset(cnt,0,sizeof cnt);
string s;cin>>s;
ans=INF;
int l=0;
for(int i=0;i<s.size();i++){
cnt[s[i]-'0']++;
while(cnt[s[l]-'0']>=2){
cnt[s[l]-'0']--;
l++;
}
if(cnt[1] && cnt[3] && cnt[2]) ans=min(ans,i-l+1);
}
if(ans==INF) cout<<0<<endl;
else cout<<ans<<endl;
}
return 0;
}
- 选项卡TabHost
- FPGA入门
- .NET 4 System.Threading.Barrier 类
- 终被捕!5名罗马尼亚黑客因入侵华盛顿政府摄像头被捕
- VUE 入门基础(9)
- 国家级人工智能产业基地落户松江,发布上海首款国产人工智能芯片
- C# 4.0 Optional Parameters 和Named Parameters
- 开源Web服务器GoAhead远程代码执行漏洞 影响数十万物联网设备
- MySpace:开源数据处理Qizmt
- 王劲:承受大风大浪,创业要忍人所不能忍
- 这枚三拼被榴莲卖了 众安科技收入囊中
- SQL Server数据库碎片
- FPGA、DSP、ARM比较
- 物联网弊端:奥地利旅馆被入侵后的反思
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法