-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbracketsequence.js
More file actions
45 lines (36 loc) · 966 Bytes
/
Copy pathbracketsequence.js
File metadata and controls
45 lines (36 loc) · 966 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
45
class Stack {
constructor() {
this.data = [];
}
push(element) {
this.data.push(element);
}
pop() {
return this.data.pop();
}
}
const bracketMap = {
"(": ")",
"[": "]",
"{": "}"
};
const doBracketsBalance = str => {
// Creating Stack
const stack = new Stack();
// Looping through each bracket in the string
for (let bracket of str) {
// If the bracket is an opening bracket push it onto the stack
if (bracketMap[bracket]) {
stack.push(bracket);
} else {
// If not, then pop a bracket off the stack.
const poppedBracket = stack.pop();
// Check to see if the popped bracket is the matching bracket
if (bracketMap[poppedBracket] !== bracket) {
return false;
}
}
}
return stack.data.length === 0;
};
console.log(doBracketsBalance('{}'));