括号匹配
- LeetCode20,碰到右括号入栈,碰到左括号判断匹配
var isValid = function(s) {
let stack = new Array();
let map = new Map();
map.set(')', '(');
map.set('}', '{');
map.set(']', '[');
for(let i = 0; i < s.length; ++i) {
if(map.has(s[i])) {
if(stack.length === 0 || map.get(s[i]) != stack.pop()) {
return false;
}
} else {
stack.push(s[i]);
}
}
return stack.length === 0;
};
最小栈
- LeetCode155,维护一个常规栈和最小值栈,当入栈值小于最小值时,在最小值栈中push其本值,否则仍在最小值栈中push原本最小值,可使查找栈中最小值时间复杂度为O(1)
var MinStack = function() {
this.stack = new Array();
this.min = new Array();
};
MinStack.prototype.push = function(val) {
this.stack.push(val);
this.min.push(Math.min(this.min.at(-1) != undefined? this.min.at(-1) : Infinity, val));
};
MinStack.prototype.pop = function() {
this.stack.pop();
this.min.pop();
};
MinStack.prototype.top = function() {
return this.stack.at(-1);
};
MinStack.prototype.getMin = function() {
return this.min.at(-1);
};