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 Pi(∣Pi∣≤2×105).
It guaranteed that the sum of ∣Pi∣≤2×105.
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