|
1 | 1 | /**
|
2 |
| - * https://leetcode.com/problems/valid-parentheses |
3 | 2 | * Time O(N) | Space O(N)
|
| 3 | + * https://leetcode.com/problems/valid-parentheses/ |
4 | 4 | * @param {string} s
|
5 | 5 | * @return {boolean}
|
6 | 6 | */
|
7 |
| - var isValid = function(s, stack = []) { |
| 7 | + var isValid = (s, stack = []) => { |
8 | 8 | for (const bracket of s.split('')) {/* Time O(N) */
|
9 | 9 | const isParenthesis = bracket === '(';
|
10 | 10 | if (isParenthesis) stack.push(')'); /* Space O(N) */
|
|
15 | 15 | const isSquareBracket = bracket === '[';
|
16 | 16 | if (isSquareBracket) stack.push(']');/* Space O(N) */
|
17 | 17 |
|
18 |
| - const isOpenBracket = isParenthesis || isCurlyBrace || isSquareBracket; |
19 |
| - if (isOpenBracket) continue; |
| 18 | + const isOpenPair = isParenthesis || isCurlyBrace || isSquareBracket; |
| 19 | + if (isOpenPair) continue; |
20 | 20 |
|
21 | 21 | const isEmpty = !stack.length;
|
22 | 22 | const isWrongPair = stack.pop() !== bracket;
|
23 | 23 | const isInvalid = isEmpty || isWrongPair;
|
24 | 24 | if (isInvalid) return false;
|
25 | 25 | }
|
26 |
| - return stack.length === 0; |
| 26 | + |
| 27 | + return (stack.length === 0); |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * Time O(N) | Space O(N) |
| 32 | + * https://leetcode.com/problems/valid-parentheses/ |
| 33 | + * @param {string} s |
| 34 | + * @return {boolean} |
| 35 | + */ |
| 36 | +var isValid = (s, stack = []) => { |
| 37 | + const map = { |
| 38 | + '}': '{', |
| 39 | + ']': '[', |
| 40 | + ')': '(', |
| 41 | + }; |
| 42 | + |
| 43 | + for (const char of s) {/* Time O(N) */ |
| 44 | + const isBracket = (char in map) |
| 45 | + if (!isBracket) { stack.push(char); continue; }/* Space O(N) */ |
| 46 | + |
| 47 | + const isEqual = (stack[stack.length - 1] === map[char]) |
| 48 | + if (isEqual) { stack.pop(); continue; } |
| 49 | + |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + return (stack.length === 0); |
27 | 54 | };
|
0 commit comments