天梯赛 7-4 括号匹配

该博客介绍了一个关于检查括号字符串是否为有效括号序列的问题。有效括号字符串需满足每种类型的括号都有相应的配对。给出了样例输入和输出,并提出了使用二维数组记录括号数量以及通过标志变量flag判断匹配性的解决方案。
摘要由CSDN通过智能技术生成

Description

Given a string P only consist of characters with (), [] and {}. Now BaoBao wants to know whether P can form a valid bracket string.

We define a pair that for each (, we can find a ) behind it. In the same way, [ and { also can find their ] and }. For example:

In string "()": ( and ) formed a pair;
In string "[)(]": [ and ] formed a pair, but ( and ) are not;
In string "{(})[{(}])", there exist 5 pairs.

And a valid bracket string means the number of pairs in a string N can satisfy N=∣P∣÷2 where ∣P∣ means the length of string P.

For example, “(()())”, “({})”, “([)]” and “{[(]})” are the valid bracket string, but “(()”, “)(” and “{ {(})” are invalid.
Input:

The first line contains a integer T(1≤T≤100), which indicates the number of test cases.

The next T lines, each line only contains a bracket string P​i​​(∣P​i​​∣≤2×10​5​​).

It guaranteed that the sum of ∣P​i​​∣≤2×10​5​​.
Output:

For each test cases, you just output “YES” if the string is valid or “NO” for not valid.
Sample Input:

4
({})
{ {}}
({[}])
}{

Sample Output:

YES
YES
YES
NO
翻译:
说明
给定一个字符串P只能由带有()、[]和{}的字符组成。现在宝宝想知道P是否能形成一个有效的括号字符串。
我们定义了一对,每个(,我们可以找到一个)后面。以同样的方式,[和{也可以找到他们的]和}。例如:
在字符串“()”:(和)中形成一对;
在字符串“[)(]”中:[和]组成一对,但(和)不是;
在字符串“{(})[{(}])”中,存在5对。
一个有效的括号字符串表示一个字符串中的对数N可以满足N=∣P∣÷2,其中∣P∣表示字符串P的长度。
例如,“(())”、“({})”、“([)]”和“{[(]})”是有效的括号字符串,但“(()”、“)”和“{ {(})”无效。
输入:
第一行包含一个整数T(1≤T≤100),表示测试用例的数量。
接下来的T行,每行只包含一个括号字符串pi(∣pi∣≤2×105)。
它保证了∣pi∣之和≤2×105。
输出:
对于每个测试用例,如果字符串有效,则只输出“YES”,如果字符串无效,则输出“NO”。
思路:我们用一个二维数组来存储每种括号的数量,一维表示种类,二维表示前后括号。然后没输入一个字符相应数量加一,最后判断每种括号的前后种类是否相等。
注意:有可能出现括号的前后种类相等但是不匹配的情况,如一对括号右括号在左括号之前,所以我们得想办法判断,这里用flag判断。

#include <iostream>
#include <algorithm>
#include <stdio.h> 
#include <string>
using namespace std;
int a[3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乔梦圆的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值