-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.js
More file actions
56 lines (48 loc) · 1.24 KB
/
task.js
File metadata and controls
56 lines (48 loc) · 1.24 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
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return null;
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
function isBalanced(expression) {
const stack = new Stack();
const openingBrackets = "({[";
const closingBrackets = ")}]";
const matchingBrackets = {
")": "(",
"}": "{",
"]": "[",
};
for (const char of expression) {
if (openingBrackets.includes(char)) {
stack.push(char);
} else if (closingBrackets.includes(char)) {
if (stack.isEmpty() || stack.pop() !== matchingBrackets[char]) {
return false;
}
}
}
return stack.isEmpty();
}
// Test cases
console.log(isBalanced("(a + b) * (c - d)")); // Output: true
console.log(isBalanced("{[()]}")); // Output: true
console.log(isBalanced("{[(])}")); // Output: false
console.log(isBalanced("((a + b)")); // Output: false