【c++】【Data Structure_Stack】Balanced parentheses

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

  1. S is an empty string; or

  2. S = ABwhere bothAandBare balanced; or

  3. 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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值