Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit dc475b9

Browse files
authored
Update 20-Valid-Parentheses.js
1 parent 5a81efd commit dc475b9

File tree

1 file changed

+45
-16
lines changed

1 file changed

+45
-16
lines changed

javascript/20-Valid-Parentheses.js

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,54 @@
11
/**
2+
* Time O(N) | Space O(N)
3+
* https://leetcode.com/problems/valid-parentheses/
24
* @param {string} s
35
* @return {boolean}
46
*/
5-
var isValid = function(s) {
6-
let stack = [];
7-
let map = {
7+
var isValid = (s, stack = []) => {
8+
for (const bracket of s.split('')) {/* Time O(N) */
9+
const isParenthesis = bracket === '(';
10+
if (isParenthesis) stack.push(')'); /* Space O(N) */
11+
12+
const isCurlyBrace = bracket === '{';
13+
if (isCurlyBrace) stack.push('}'); /* Space O(N) */
14+
15+
const isSquareBracket = bracket === '[';
16+
if (isSquareBracket) stack.push(']');/* Space O(N) */
17+
18+
const isOpenPair = isParenthesis || isCurlyBrace || isSquareBracket;
19+
if (isOpenPair) continue;
20+
21+
const isEmpty = !stack.length;
22+
const isWrongPair = stack.pop() !== bracket;
23+
const isInvalid = isEmpty || isWrongPair;
24+
if (isInvalid) return false;
25+
}
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 = {
838
'}': '{',
939
']': '[',
10-
')':'(',
40+
')': '(',
1141
};
12-
if(s.length < 2) return false;
13-
for(let i=0; i<s.length; i++){
14-
if(s[i] in map){
15-
if(stack[stack.length-1] == map[s[i]]){
16-
stack.pop();
17-
} else{
18-
return false;
19-
}
20-
} else {
21-
stack.push(s[i]);
22-
}
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;
2351
}
24-
return stack.length == 0;
52+
53+
return (stack.length === 0);
2554
};

0 commit comments

Comments
 (0)