您的位置:首页 > 其它

UVa673 Parentheses Balance

2014-03-20 14:52 429 查看
// 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: