-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathValidParentheses.js
43 lines (38 loc) · 1.08 KB
/
ValidParentheses.js
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
36
37
38
39
40
41
42
43
// Source : https://oj.leetcode.com/problems/valid-parentheses/
// Author : Dean Shi
// Date : 2015-06-11
/**********************************************************************************
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
* determine if the input string is valid.
*
* The brackets must close in the correct order, "()" and "()[]{}" are all valid
* but "(]" and "([)]" are not.
*
*
**********************************************************************************/
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const stack = []
const openChars = new Set('({[');
const closeChars = {
'(': ')',
'{': '}',
'[': ']',
}
for (let ch of s) {
if (openChars.has(ch)) {
stack.push(ch)
} else if (closeChars[stack.pop()] !== ch) {
return false
}
}
return stack.length === 0
};
// Test cases
console.log(isValid('()[]{}')); // true
console.log(isValid('(]')); // false
console.log(isValid('([)]')); // false