Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 43f48ab

Browse files
author
tumanob
committed
Create ValidParentheses_p20.js
Add JS solution for - 20. Valid Parentheses
1 parent 4330135 commit 43f48ab

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎JsSolutions/ValidParentheses_p20.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* https://leetcode.com/problems/valid-parentheses/
3+
*
4+
* stack Data structure example
5+
* https://initjs.org/data-structure-stack-in-javascript-714f45dbf889
6+
*
7+
*/
8+
9+
/**
10+
* @param {string} s
11+
* @return {boolean}
12+
*/
13+
var isValid = function (s) {
14+
if (s.length == 1) return false
15+
if (s.length == 0) return true
16+
17+
let stack = []
18+
let myMap = new Map()
19+
myMap.set('(', ')')
20+
myMap.set('{', '}')
21+
myMap.set('[', ']')
22+
23+
for (char of s) { // complexity in O(N) as we go throught the string once
24+
if (char === '(' || char === '{' || char === '[') {
25+
stack.push(char) // in worst case it gives another O(N) in space and time "((((((..."
26+
} else {
27+
if (char !== myMap.get(stack[stack.length - 1]))
28+
return false
29+
stack.pop()
30+
}
31+
}
32+
33+
return stack.length === 0
34+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /