-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathValidParenthesis.js
53 lines (45 loc) · 1.21 KB
/
ValidParenthesis.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
// Valid Parenthesis:
const isValidParenthesis = function(s) {
let stack = [];
for (let i = 0; i < s.length; i++) {
if (s[i] == "(") {
stack.push(")");
} else if (s[i] == "[") {
stack.push("]");
} else if (s[i] == "{") {
stack.push("}");
} else if (stack.pop() !== s[i]) {
return false;
}
}
return stack.length === 0;
};
let a = "()[]{}"; // true
let b = "([[])"; // false
isValidParenthesis(a);
// Updated version:
function isValidParentheses(str) {
let validOpenMap = {
"{": "}",
"[": "]",
"(": ")"
};
let validCloseMap = {
"}": true,
")": true,
"]": true,
};
let stack = [];
for (let i = 0; i < str.length; i++) {
if (validOpenMap[str[i]]) {
stack.push(validOpenMap[str[i]]);
} else if (validCloseMap[str[i]] && stack.pop() !== str[i]) {
return false;
}
}
return stack.length === 0;
}
console.log(isValidParentheses("[{dsfdsfdasdas}{}adsfdsfdsf}]") === false);
console.log(isValidParentheses("sd[{dsfdsdas}dsf{dsf{adsf}adsfdsf}]") === true);
console.log(isValidParentheses("[({})]") === true);
console.log(isValidParentheses("[(])") === false);