-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathValidParentheses.js
More file actions
35 lines (29 loc) · 873 Bytes
/
ValidParentheses.js
File metadata and controls
35 lines (29 loc) · 873 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
*/
const isValidParentheses = function (s) {
const map = {
"(": ")",
"{": "}",
"[": "]",
};
let stack = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "(" || s[i] === "{" || s[i] === "[") {
stack.push(s[i]);
} else {
if (map[stack.pop()] !== s[i]) return false;
}
}
return stack.length ? false : true;
};
console.log(isValidParentheses("()"));
console.log(isValidParentheses("({[}])"));
console.log(isValidParentheses("(]"));
console.log(isValidParentheses("([)]"));
console.log(isValidParentheses("{[]}"));
console.log(isValidParentheses("(("));