题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=614
Time limit: 3.000 seconds
Description
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
Problem solving report:
Description: 给你由'[',']','(',')'组成的字符串,问能否进行括号匹配。
Problem solving: 利用栈的性质,只要遇到能匹配的就移出栈,否则就进栈,最后再判断一下栈是否为空就行了。
#include <stack>
#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
int t;
char str[130];
scanf("%d%*c", &t);
while (t--)
{
gets(str);
stack <char> s;
for (int i = 0; str[i]; i++)
{
if (!s.empty())
{
if ((s.top() != '[' || str[i] != ']') && (s.top() != '(' || str[i] != ')'))
s.push(str[i]);
else s.pop();
}
else s.push(str[i]);
}
if (!s.empty())
printf("No\n");
else printf("Yes\n");
}
return 0;
}