Skip to content

Commit 0107708

Browse files
add balancedParentheses
1 parent 657f0a5 commit 0107708

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

balancedParentheses.js

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
* 平衡圆括号问题
3+
* 概念: {(()())}是平衡的,([]{}()})是不平衡的
4+
* 原理:从左向右查找时,第一个遇到的右括号,一定与它左侧最近的左括号匹配。
5+
* 同样,最后一个右括号,一定与第一个左括号相匹配。
6+
* 很像入栈出栈操作
7+
* */
8+
9+
var match = function(open, close) {
10+
var opens = '([{',
11+
closes = ')]}';
12+
13+
return opens.indexOf(open) === closes.indexOf(close);
14+
};
15+
16+
var balancedParentheses = function(symbols) {
17+
var stack = new Stack(),
18+
balanced = true,
19+
index = 0,
20+
len = symbols.length,
21+
symbol, top;
22+
23+
while (index < len && balanced) {
24+
symbol = symbols[index];
25+
26+
if (symbol === '(' || symbol === '[' || symbol === '{') {
27+
stack.push(symbol);
28+
} else {
29+
if (stack.isEmpty()) {
30+
balanced = false;
31+
} else {
32+
top = stack.pop();
33+
if (!match(top, symbol)) {
34+
balanced = false;
35+
}
36+
}
37+
}
38+
index++;
39+
}
40+
41+
if (balanced && stack.isEmpty()) {
42+
return true;
43+
}
44+
return false;
45+
};
46+
47+
48+
/*
49+
* 附:堆的类
50+
* */
51+
function Stack() {
52+
53+
var items = [];
54+
55+
// 添加一个元素到栈顶
56+
this.push = function(element){
57+
items.push(element);
58+
};
59+
60+
// 移除栈顶的元素并返回
61+
this.pop = function(){
62+
return items.pop();
63+
};
64+
65+
// 返回栈顶的元素,不对栈进行修改
66+
this.peek = function(){
67+
return items[items.length-1];
68+
};
69+
70+
// 栈是否为空
71+
this.isEmpty = function(){
72+
return items.length == 0;
73+
};
74+
75+
// 返回栈的元素个数
76+
this.size = function(){
77+
return items.length;
78+
};
79+
80+
// 清空栈
81+
this.clear = function(){
82+
items = [];
83+
};
84+
85+
// 打印栈
86+
this.print = function(){
87+
console.log(items.toString());
88+
};
89+
90+
// 返回栈的字符串表示
91+
this.toString = function(){
92+
return items.toString();
93+
};
94+
}

0 commit comments

Comments
 (0)