【题目描述】
字符串中只含有括号 (),[],<>,{}
,判断输入的字符串中括号是否匹配。如果括号有互相包含的形式,从内到外必须是<>,(),[],{}
,例如。输入: [()]
输出:YES
,而输入([]),([)]
都应该输出NO
。
【输入】
第一行为一个整数nn,表示以下有多少个由括好组成的字符串。接下来的nn行,每行都是一个由括号组成的长度不超过255255的字符串。
【输出】
在输出文件中有nn行,每行都是YES
或NO
。
【输入样例】
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
><}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
【输出样例】
YES
YES
YES
YES
NO
思路:
入栈的时候判断一下顺序,出栈时正常判断就行。
代码:
#include<iostream>
#include<cstring>
#include<cstring>
using namespace std;
bool judge(string s)
{
char st[300];
memset(st,0,sizeof(0));
int top=-1;
for(int i=0;i<s.length();i++)
{
if(s[i]=='<')st[++top]=s[i];
if(s[i]=='>'){
if(st[top]=='<')top--;
else return 0;
}
if(s[i]=='('){
if(top>-1&&st[top]=='<')return 0;
else st[++top]=s[i];
}
if(s[i]==')'){
if(st[top]=='(')top--;
else return 0;
}
if(s[i]=='['){
if(top>-1&&(st[top]=='<'||st[top]=='('))return 0;
else st[++top]=s[i];
}
if(s[i]==']'){
if(st[top]=='[')top--;
else return 0;
}
if(s[i]=='{'){
if(top>-1&&(st[top]=='<'||st[top]=='('||st[top]=='['))return 0;
else st[++top]=s[i];
}
if(s[i]=='}'){
if(st[top]=='{')top--;
else return 0;
}
}
if(top==-1)return 1;
else return 0;
}
int main()
{
int n;
cin>>n;
while(n--)
{
string s;
cin>>s;
if(judge(s))cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}