-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path20. Valid Parentheses.js
57 lines (50 loc) · 1.07 KB
/
20. 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
46
47
48
49
50
51
52
53
54
55
56
57
/*
20. Valid Parentheses
https://leetcode.com/problems/valid-parentheses/
*/
/* TIME COMPLEXITY IS O(N) */
/*
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
*/
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
if (s.length == 1) {
return false;
}
var map = {
")": "(",
"]": "[",
"}": "{"
}
var contain = [];
for (let i = 0; i < s.length; i++) {
if ("{" === s[i] || "[" === s[i] || "(" === s[i]) {
contain.push(s[i]);
} else {
if (contain.length == 1) {
if (contain[0] === map[s[i]]) {
contain.splice(0, 1);
} else { return false }
} else {
if (contain[i - 1] === map[s[i]]) {
contain.splice(i - 1, 1);
} else {
return false;
}
}
}
}
return contain.length > 0 ? "false" : "true";
};
console.log(isValid("({"));