给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。
输入格式:
第一行一个整数T(T<=10)
其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)
输出格式:
对于每个字符串,匹配输出Yes,否则输出No
输入样例:
2
{()[]}
([)]
输出样例:
Yes
No
Code:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
const int INF=0x3f3f3f3f;
typedef long long LL;
const int mod=1e9+7;
using namespace std;
#define STACK_SIZE 32
#define Num 500005
typedef struct{
char *base;
char *top;
int size;
}Stack;
int InitStack(Stack *s){
s->base = (char *)malloc(STACK_SIZE* sizeof(Stack));
s->top = s->base;
s->size = STACK_SIZE;
return 1;
}
int Push(Stack *s,char x){
*s->top = x;
s->top++;
return 1;
}
int Pop(Stack *s,char *x){
if(s->top == s->base)return 0;
else{
s->top--;
*x = *s->top;
return 1;
}
}
int GetTop(Stack *s, char *x){
if(s->top==s->base)return 0;
else{
*x=*(s->top-1);
return 1;
}
}
int Match(char a,char b)
{
if(a=='{'&&b=='}'||a=='['&&b==']'||a=='('&&b==')')
return 1;
else return 0;
}
int BMatch(char *str){
Stack s;
int i,flag=1;
char ch;
InitStack(&s);
for (i=0;str[i]!=0;i++) {
switch(str[i])
{
case '(':
case '[':
case '{':Push(&s,str[i]);
break;
case ')':
case ']':
case '}':GetTop(&s,&ch);
if (Match(ch,str[i]))
{
Pop(&s,&ch);
}else{
flag = 0;
}
}
}
if(i%2 != 0) flag = 0;
if(flag) return 1;
else return 0;
}
int main(){
int turn;
cin>>turn;
for(int i = 0; i < turn; i++){
char c[Num];
char* rrr = c;
scanf("%s",c);
if(BMatch(rrr) == 1) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}