1、 问题描述
In this question, you shall write a program to determine whether a string is balanced parentheses using stack.
We call a string S balanced parentheses if
-
S is an empty string; or
-
S = ABwhere bothAandBare balanced; or
-
S = (T) or S = [T] or S = {T} whereT is balanced.
For example, ( [ ] { } ) is balanced but ( [ ) ] and ( ( ) are not.
(a) Implement the stack abstract data type by either array or linked list. You mayassume the maximum size needed is at most 10000
(b) Solve the balanced parentheses problem using stack. If the input string has lengthm, your program should run inO(m) time.
Input: The first line has an integern, the number of testcases. Each of the following n lines contains a strings, which consists of bracket characters ( ) [ ] { } only.
Ourtestcases satisfies1 <= n <= 1000and1 <= length(s) <= 10000.
Output:For each testcase output Yes if the string is balanced or No otherwise.
Sample Input:
4
([]{})
([)]
(()
(){()[]}
Sample Output:
Yes
No
No
Yes
No libraries other than cstdio,cstring,iostream and string shall be used.
Only correctness and efficiency would be tested, so you do not have to write comments for your codes.
2、整体思路
括号匹配,运用栈的思想,只将左括号进栈。
如果是左括号,则进栈;如是右括号,则一定与栈顶匹配,若不匹配就是错误的,且最后栈一定为空才行。
3、构造 Node 和 Stack 类
Node 类 构造 Node 的 value 和 下一个节点的指针
class Node {
public:
char c;
Node *next;
};
Stack 类 构造 [包括 print_all() , top(), push (element c), pop() ]
class Stack {
private:
Node *header;
public:
Stack() {
header = NULL; //创造函数,构造一个指向空 Node 类型header
}
void print_all() {
// 打印Stack所有的value
for (Node* iter = header; iter