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
————————————————————————————————————————————————————
代码:
#include<iostream>
#include<string.h>
#include<cstdio>
#include<stack>
using namespace std;
int main()
{
char str[128 + 10];
int n;
scanf("%d", &n);
getchar();
while (n--)
{
fgets(str, 128 + 10, stdin);
int len = strlen(str);
if (str[len - 1] == '\n')
len--;
stack<char> q;
for (int i = 0; i < len; i++)
{
if (str[i] == '(' || str[i] == '[')
q.push(str[i]);
else
{
if (q.empty())
{
q.push(str[i]);
break;
}
if (q.top() == '(' && str[i] == ')' ||
q.top() == '[' && str[i] == ']')
q.pop();
else
break;
}
}
if (q.empty())
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
分析:
这是一个经典的关于栈的应用的题目——括号配对.第一次提交的时候是 Wrong Answer.再次读题才发现错误所在:
(a)
543

被折叠的 条评论
为什么被折叠?



