一个后进先出的数据结构,例如蜂窝煤,先放进去的蜂窝煤是被后拿出来的,后放进去的先拿出来,放进去(push)拿出来(pop)

JavaScript虽然没有栈,但是可以通过array进行实现

1
2
3
4
5
6
const stack = []
stack.push(1)
stack.push(2)

const item1 = stack.pop()
const item2 = stack.pop()

题目 有效括号

https://leetcode-cn.com/problems/valid-parentheses/

思路:使用栈的特性实现

时间复杂度:O(n)

空间复杂度:O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @param {string} s
* @return {boolean}
*/
var obj = {
'(': ')',
'{': '}',
'[': ']'
}
var isValid = function (s) {
if (s.length % 2 === 1) {
return false
}
const stack = []
for (let i = 0; i < s.length; i++) {
if (obj[s[i]]) {
stack.push(s[i])
} else {
if (obj[stack[stack.length - 1]] === s[i]) {
stack.pop()
} else {
return false
}
}
}
return stack.length === 0
};

函数调用堆栈