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,就要用 getline(cin,a). 还要注意的是,前面几组数据那里也有个换行。要用 getchar() 消除掉;然后就是栈的应用了。
AC 代码:
- #include#include#include < string.h > #include using namespace std;
- int main() {
- int t;
- cin >> t;
- getchar();
- while (t--) {
- string a;
- stack < char > c;
- getline(cin, a);
- if (a[0] == '\n') {
- cout << "Yes" <
- continue;
- }
- c.push('1');
- for (int i = 0; i) {
- if (a[i] == ' (' || a[i] == ' [') c.push(a[i]);
- else if (a[i] == ')') {
- if (c.top() == ' (') c.pop();
- else c.push('0');
- } else {
- if (c.top() == ' [') c.pop();
- else c.push('0');
- }
- }
- if (c.top() == '1') cout << "Yes" << endl;
- else cout << "No" << endl;
- }
- return 0;
- }
来源: http://www.bubuko.com/infodetail-2220527.html