-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0020-valid-parentheses.js
More file actions
62 lines (52 loc) · 1.5 KB
/
0020-valid-parentheses.js
File metadata and controls
62 lines (52 loc) · 1.5 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Time O(N) | Space O(N)
* https://leetcode.com/problems/valid-parentheses/
* @param {string} s
* @return {boolean}
*/
var isValid = (s, stack = []) => {
for (const bracket of s.split('')) {
/* Time O(N) */
const isParenthesis = bracket === '(';
if (isParenthesis) stack.push(')'); /* Space O(N) */
const isCurlyBrace = bracket === '{';
if (isCurlyBrace) stack.push('}'); /* Space O(N) */
const isSquareBracket = bracket === '[';
if (isSquareBracket) stack.push(']'); /* Space O(N) */
const isOpenPair = isParenthesis || isCurlyBrace || isSquareBracket;
if (isOpenPair) continue;
const isEmpty = !stack.length;
const isWrongPair = stack.pop() !== bracket;
const isInvalid = isEmpty || isWrongPair;
if (isInvalid) return false;
}
return stack.length === 0;
};
/**
* Time O(N) | Space O(N)
* https://leetcode.com/problems/valid-parentheses/
* @param {string} s
* @return {boolean}
*/
var isValid = (s, stack = []) => {
const map = {
'}': '{',
']': '[',
')': '(',
};
for (const char of s) {
/* Time O(N) */
const isBracket = char in map;
if (!isBracket) {
stack.push(char);
continue;
} /* Space O(N) */
const isEqual = stack[stack.length - 1] === map[char];
if (isEqual) {
stack.pop();
continue;
}
return false;
}
return stack.length === 0;
};