-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsolution1.js
More file actions
32 lines (32 loc) · 835 Bytes
/
solution1.js
File metadata and controls
32 lines (32 loc) · 835 Bytes
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
28
29
30
31
32
/**
* https://leetcode-cn.com/problems/valid-parentheses/
*
* 20. 有效的括号
*
* Easy
*
* 52ms 99.24%
* 35.4mb 23.61%
*/
const isValid = s => {
const stack = [];
for (let i = 0, max = s.length; i < max; i++) {
const stackIndex = stack.length - 1;
if (
(s[i] === ')' && stack[stackIndex] === '(') ||
(s[i] === '}' && stack[stackIndex] === '{') ||
(s[i] === ']' && stack[stackIndex] === '[')
) {
stack.pop();
continue;
} else if (
(s[i] === ')' && (stack[stackIndex] === '{' || stack[stackIndex] === '[')) ||
(s[i] === '}' && (stack[stackIndex] === '(' || stack[stackIndex] === '[')) ||
(s[i] === ']' && (stack[stackIndex] === '{' || stack[stackIndex] === '('))
) {
return false;
}
stack.push(s[i]);
}
return stack.length === 0;
}