Skip to content

Commit 5a81efd

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

File tree

1 file changed

+19
-21
lines changed

1 file changed

+19
-21
lines changed

javascript/20-Valid-Parentheses.js

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
11
/**
2-
* https://leetcode.com/problems/valid-parentheses
3-
* Time O(N) | Space O(N)
42
* @param {string} s
53
* @return {boolean}
64
*/
7-
var isValid = function(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 isOpenBracket = isParenthesis || isCurlyBrace || isSquareBracket;
19-
if (isOpenBracket) continue;
20-
21-
const isEmpty = !stack.length;
22-
const isWrongPair = stack.pop() !== bracket;
23-
const isInvalid = isEmpty || isWrongPair;
24-
if (isInvalid) return false;
5+
var isValid = function(s) {
6+
let stack = [];
7+
let map = {
8+
'}': '{',
9+
']': '[',
10+
')':'(',
11+
};
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+
}
2523
}
26-
return stack.length === 0;
24+
return stack.length == 0;
2725
};

0 commit comments

Comments
 (0)