C. Dominant Character

传送门

题意:给你一个字符串,这个字符串只由'a','b','c'组成,让你求最短的一个字串,满足下面三个条件:

  • 最小子串的长度至少为 2

  • ‘a’ 在这个子字符串中出现的次数比在 ‘b’ 中出现的次数要多

  • ‘a’ 在这个子字符串中出现的次数比在 ‘c’ 中出现的次数要多

让你输出这个字符串的最短长度。

思路:

从最短到最长的情况进行考虑

首先如果是a有两个的情况,aa,aXa,aXXa都能满足(两个a中间要保证'b','c'最多只出现一次)

如果是三个a,那么每两个a中间一定要有两个b或者两个c,满足的条件就只有abbacca或者accabba

如果是四个a,因为每两个a中间要有两个b或者两个c或者更多,那么无论怎么组合一定没有合法的答案。

那么只要找2个a的情况和3个a的情况的答案就可以了

直接遍历一遍,然后找每两个相邻的a,如果中间两个是相同的就再往后判断一个。

代码:


#include<cstdio>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include<vector>
#include<queue>
#include<map>
#define sc_int(x) scanf("%d", &x)
#define sc_ll(x) scanf("%lld", &x)
#define pr_ll(x) printf("%lld", x)
#define pr_ll_n(x) printf("%lld\n", x)
#define pr_int_n(x) printf("%d\n", x)
#define ll long long 
using namespace std;

const int N=2000000+100;
int n ,m,h;
char s[N];

void solve()
{
	cin>>n>>s+1;

	int res=1e9;
	int l=0,r=0;
	for(int i =1;i<=n;i++)
	{
		if(s[i]=='a')
		{

			if(!l)l=i;
			else {
				r=i;
				int b=0,c=0;

				for(int j =l+1;j<r;j++)
				if(s[j]=='b')b++;
				else c++;
				
				if(max(b,c)<2)
				res=min(res,r-l+1);
				else {
					if(((b==2&&c==0&&s[r+1]=='c'&&s[r+2]=='c'&&s[r+3]=='a')||(c==2&&b==0&&s[r+1]=='b'&&s[r+2]=='b'&&s[r+3]=='a'))&&r+3<=n)
					res=min(res,7);
				}
				l=i;
			}
		}
	}
	if(res!=1e9)
	cout<<res<<endl;
	else cout<<"-1\n";
	
	return ;
}


int main()
{
	int t;
	sc_int(t);
	while(t--)solve();
	
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值