forked from xiaoyu2er/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path020-Valid-Parentheses.js
45 lines (39 loc) · 1.04 KB
/
020-Valid-Parentheses.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
44
45
/**
* https://leetcode.com/problems/valid-parentheses/
* Difficulty:Easy
*
* 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) {
var stack = [];
for (var i = 0; i < s.length; i++) {
var c = s[i];
switch (c) {
case '(':
stack.push(')');
break;
case '[':
stack.push(']');
break;
case '{':
stack.push('}');
break;
default:
if (!stack.length || stack.pop() !== c) {
// console.log(stack);
return false;
}
}
}
return stack.length === 0;
};
console.log(isValid('()[]{}'));
console.log(isValid('[()][]{}'));
console.log(isValid('(])'));