A.ABC String

problem

在这里插入图片描述
Chinese Language
在这里插入图片描述

This is just a translation of the main meaning
Example

input
4
AABBAC
CACA
BBBBAC
ABCA
output
YES
YES
NO
NO
Note
In the first testcase one of the possible strings b is “(())()”.
In the second testcase one of the possible strings b is “()()”.

Code and Analysis

#include<iostream>
using namespace std;
string s;
int n;
bool ans=false;
int st[3]={0,-1,1};//Let the closing bracket be -1 and the opening bracket be 1
int box[5],vis[5];
//Judging the type of brackets represented by each ABC
bool check(int a,int b,int c)
{
	int x=0;
	for(int i=0;i<n;i++)
	{
		if(s[i]=='A') x+=a;
		if(s[i]=='B') x+=b;
		if(s[i]=='C') x+=c;
		if(x<0)return false;
	}
	return x==0? true:false;
}
//Traverse all combinations of ABC
void recursion(int flag)
{
	if(flag>3)
	{
		if(check(box[1],box[2],box[3]))
		{
			ans=true;
		}
		return ;
	}
	for(int i=1;i<=2;i++)
	{
		if(vis[flag]==0)
		{
			box[flag]=st[i];
			vis[flag]=1;
			recursion(flag+1);
			vis[flag]=0;
		}
	}
}

int main()
{
	int T ;
	cin>>T ;
	while(T--)
	{
		ans=false;
		cin>>s;
		n=s.length();
		recursion(1);
		if(ans)cout<<"YES"<<'\n';
		else cout<<"NO"<<'\n';	 
	}
	return 0;
}

If the previous code is a bit difficult to understand, you can look at the following code

#include<iostream>
std::string s;
int n;
bool check(int a, int b, int c){
	int x = 0;
	for(int i=0;i<n; i++){
		if(s[i] == 'A'){
			x += a;
		}
		if(s[i] == 'B'){
			x += b;
		}
		if(s[i] == 'C'){
			x += c;
		}
		if (x<0){
			return false;
		}
	}
	return x == 0;//'==' means judgment here.
	//Returns true if the judgment result is true, otherwise returns false
}
int main()
{
	int T;
	std :: cin>>T;
	for(int cas =1; cas<=T; cas++){
		std::cin>>s ;
		n = s.length();
		bool ans = false ;
		for(int a =-1;  a<= 1; a+=2)
			for(int b=-1;   b<=1;b+=2)
				for(int c=-1;  c<=1; c+=2)
				if(check(a,b,c)){
					ans = true;
					goto flag;
				}
		flag:;
		std::cout<< (ans ? "YES\n" : "NO\n");
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值