UVa673 Parentheses Balance

时间:2023-03-08 21:35:03

// UVa673 Parentheses Balance
// 题意:输入一个包含()和[]的括号序列,判断是否合法。
// 具体递归定义如下:1.空串合法;2.如果A和B都合法,则AB合法;3.如果A合法则(A)和[A]都合法。
// 算法:用一个栈。注意输入可能有空串

#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std; int main()
{
int n;
scanf("%d", &n); getchar();
char s[256];
while(n--)
{
gets(s);
// puts(s);
int len=strlen(s);
stack<char> st;
char c;
bool ok=true;
for(int i=0;i<len&&ok;i++)
{
switch(s[i])
{
case '(':
case '[':
st.push(s[i]);
break;
case ')':
case ']':
if(st.empty())
ok=false;
else
{
c=st.top(); st.pop();
if(s[i]==')' && c!='(')
ok=false;
else if(s[i]==']' && c!='[')
ok=false;
}
break;
}
}
if(ok&&st.empty())
printf("Yes\n");
else
printf("No\n"); } return 0;
}