You are given a bracket sequence ss of length nn, You need to determine whether the given string is a regular bracket sequence.
Recall what the regular bracket sequence is:
- "()" is regular bracket sequence;
- if ss is regular bracket sequence then "(" + ss + ")" is regular bracket sequence;
- if ss and tt are regular bracket sequences then ss + tt is regular bracket sequence.
For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.
Input
The first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then tt test cases follow.
The first line of the test case contains one integer nn (1≤n≤2⋅10^51≤n≤2⋅105) — the length of ss. The second line of the test case containg the string ss.
Output
For each test case, print YES if the given string is a regular bracket sequence, or NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).
Sample 1
Inputcopy | Outputcopy |
---|---|
2 6 (()()) 4 )()( | YES NO |
#include<stdio.h>
#include<string.h>
#define length 100
char *top;
char push(char bracket){
top=top+1;
*(top)=bracket;
}
void pop()
{
top=top-2;
}
int main()
{ int n;
scanf("%d",&n);
while(n--){
int l=0;
scanf("%d",&l);
char array[l];
char stack[l];
scanf("%s",array);
int stack_length=strlen(array);
top=stack-1;
for(int i=0;i<stack_length;i++){
push(array[i]); //每一个步骤都先把数组里的括号压入栈里
if(array[i] == ']'){ //如果压入的是 ] 号,
if(*(top-1) == '['){ //就在当前位置往下一个单位判断有没有 [ 号,如果有,就弹出栈
pop();
}
}
if(array[i] == ')'){
if(*(top-1) == '('){
pop();
}
}
if(array[i] == '}'){
if(*(top-1) == '{'){
pop();
}
}
}
if(top == stack-1){
printf("YES\n");
}
else{
printf("NO\n");
}
}
}