Parentheses Balance
Parentheses Balance |
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
-
(a)
- if it is the empty string (b)
- if A and B are correct, AB is correct, (c)
- if A is correct, (A ) and [A ] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [] , one string a line.Output
A sequence of Yes or No on the output file.Sample Input
3 ([]) (([()]))) ([()[]()])()
Sample Output
Yes No Yes
这一个简答的题竟然提交了五遍真是醉了。
错误的原因
第一空字符串输出yes,注意到这个了,也有判断条件,还是不对,因为输入用的scanf,当输入空行是没反应,最后换成了gets
第二第二个样例老是意外中断,一直没发现问题,最后意识到是当')'或者‘】'多的时候,栈已经空了,此时取不到栈顶元素,所以意外退出
第三自己构造了一些样例不对,最后发现是在每一次的输入前没有清空栈
就是这些问题,
#include <iostream>
#include<cstring>
#include<cstdio>
#include<stack>
using namespace std;
stack<char> Stack;
int main()
{
int t;
scanf("%d",&t);
getchar();
while(t--)
{
char s[150];
gets(s);
int len=strlen(s);
if(len==0) printf("Yes\n");
else
{
int flag=0;
while(Stack.size())
Stack.pop();
for(int i=0;i<len;i++)
{
char ch;
if(s[i]=='(' || s[i]=='[')
Stack.push(s[i]);
if(s[i]==')')
{
if(Stack.size()==0)
{
flag=1;
break;
}
else
{
ch=Stack.top();
if(ch=='(')
Stack.pop();
else
{
flag=1;
break;
}
}
}
if(s[i]==']')
{
if(Stack.size()==0)
{
flag=1;
break;
}
else
{
ch=Stack.top();
if(ch=='[')
Stack.pop();
else
{
flag=1;
break;
}
}
}
}
if(!flag && Stack.size()==0)
printf("Yes\n");
else printf("No\n");
}
}
return 0;
}