-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidParenthesis.js
More file actions
44 lines (43 loc) · 920 Bytes
/
validParenthesis.js
File metadata and controls
44 lines (43 loc) · 920 Bytes
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
const validParenthesis = (str) => {
let map = {
"(": ")",
"[": "]",
"{": "}"
};
var stack = [];
for (var i = 0; i < str.length ; i ++){
if (map[str[i]]){
stack.push(map[str[i]]);
} else {
if (str[i] !== stack.pop()){
return false;
}
}
}
return stack.length === 0;
};
// validParenthesis('{()}');
const validParenthesisRecursive = (str) => {
let map = {
"(":")",
"{":"}",
"[":"]"
};
let stack = [];
let count = 0;
const recurse = (str) => {
if (count < str.length){
if (map[str[count]]){
stack.push(map[str[count]]);
} else {
if (str[count] !== stack.pop()){
return false;
}
}
count++;
recurse(str);
}
};
recurse(str);
return stack.length === 0;
};