-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathValidParentheses.js
More file actions
64 lines (53 loc) · 1.26 KB
/
ValidParentheses.js
File metadata and controls
64 lines (53 loc) · 1.26 KB
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
58
59
60
61
62
63
64
/**
* 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.
*
* Accepted.
*/
/**
* @param {string} s
* @return {boolean}
*/
let isValid = function (s) {
if (s == null || s.length === 0 || s.length === 1) {
return false;
}
let list = [];
s.split('').forEach(function (c) {
if (list.length !== 0 && ((c === ")" && list[list.length - 1] === "(")
|| (c === "]" && list[list.length - 1] === "[")
|| (c === "}" && list[list.length - 1] === "{"))) {
list.splice(list.length - 1, 1);
} else {
list.push(c);
}
});
// console.log(list);
return list.length === 0;
};
if (isValid("()")) {
console.log("pass")
} else {
console.error("failed")
}
if (isValid("()[]{}")) {
console.log("pass")
} else {
console.error("failed")
}
if (!isValid("(")) {
console.log("pass")
} else {
console.error("failed")
}
if (!isValid("(]")) {
console.log("pass")
} else {
console.error("failed")
}
if (!isValid("([)]")) {
console.log("pass")
} else {
console.error("failed")
}