-
Notifications
You must be signed in to change notification settings - Fork 0
/
BracketBalancer.ts
34 lines (28 loc) · 1.07 KB
/
BracketBalancer.ts
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
export class BracketBalancer {
static isBalanced(expression: string): boolean {
const stack: string[] = [];
for (const ch of expression) {
if (ch === '{' || ch === '(' || ch === '[') {
stack.push(ch);
} else if (ch === '}' || ch === ')' || ch === ']') {
if (stack.length === 0) return false;
const last = stack.pop() as string;
if (!BracketBalancer.isPairValid(last, ch)) {
return false;
}
}
}
return stack.length === 0;
}
private static isPairValid(open: string, close: string): boolean {
return (open === '{' && close === '}') ||
(open === '(' && close === ')') ||
(open === '[' && close === ']');
}
static main(): void {
console.log(BracketBalancer.isBalanced("{{(){}}}")); // true
console.log(BracketBalancer.isBalanced("}{}{")); // false
console.log(BracketBalancer.isBalanced("({})")); // true
}
}
BracketBalancer.main();