-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathparentheses.js
More file actions
41 lines (33 loc) · 1.06 KB
/
parentheses.js
File metadata and controls
41 lines (33 loc) · 1.06 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
//Quick program to check if parentheses are balanced in a string
//
function parenthesesChecker(string) {
let types = {
'[': {position: 'open', type: 'brace'},
']': {position: 'closed', type: 'brace'},
'{': {position: 'open', type: 'curly'},
'}': {position: 'closed', type: 'curly'},
'(': {position: 'open', type: 'parentheses'},
')': {position: 'closed', type: 'parentheses'},
};
let currentStack = [];
for(let i = 0; i < string.length; i++){
let currentBrace = string[i];
let braceInfo = types[currentBrace];
if (braceInfo.position === 'closed'){
let lastBrace = currentStack.pop();
if (!(lastBrace)){
return false;
}
if (!(lastBrace.position === 'open' && lastBrace.type === braceInfo.type)){
return false;
}
} else {
currentStack.push(braceInfo);
}
}
return !currentStack.length;
}
console.log(parenthesesChecker("{}()"));
console.log(parenthesesChecker("{})"));
console.log(parenthesesChecker("[]{}()"));
console.log(parenthesesChecker("[{}]()"));