Skip to content

Commit 2bc42e6

Browse files
committed
add: validParentheses solution
1 parent 72a46d1 commit 2bc42e6

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

valid-parentheses/Cyjin-jani.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// tc: O(n)
2+
// sc: O(n)
3+
const isValid = function (s) {
4+
const bracketMap = {
5+
'(': ')',
6+
'{': '}',
7+
'[': ']',
8+
};
9+
10+
if (s.length % 2 !== 0 || isCloseBracket(s[0])) return false;
11+
12+
const stack = [];
13+
14+
for (let i = 0; i < s.length; i++) {
15+
if (stack.length === 0) {
16+
stack.push(s[i]);
17+
continue;
18+
}
19+
20+
let topBracket = stack.pop();
21+
if (bracketMap[topBracket] !== s[i]) {
22+
stack.push(topBracket);
23+
stack.push(s[i]);
24+
}
25+
}
26+
27+
return stack.length === 0;
28+
};
29+
30+
function isCloseBracket(char) {
31+
const closeBrackets = [')', '}', ']'];
32+
33+
return closeBrackets.includes(char);
34+
}

0 commit comments

Comments
 (0)