Last active
April 6, 2023 17:28
-
-
Save Toscan0/1bc623a6a9b9c696aebdf1095202f5b2 to your computer and use it in GitHub Desktop.
Check if an expression is balanced or not. Return the index. if not balanced
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const checkBalancedExpr = (expr) => { | |
let stack = []; | |
for(let i = 0; i < expr.length; i++) { | |
let char = expr[i]; | |
const brackets = ['(', ')', '[', ']', '{', '}'] | |
if(!brackets.includes(char)) { | |
continue; | |
} | |
if (char === '(' || char === '[' || char === '{') { | |
stack.push(char); | |
continue; | |
} | |
if (stack.length === 0) { | |
return [false, i]; | |
} | |
let check = stack.pop(); | |
switch (char) { | |
case ')': | |
if (check !== '(') { | |
return [false, i]; | |
} | |
break; | |
case '}': | |
if (check !== '{') { | |
return [false, i]; | |
} | |
break; | |
case ']': | |
if (check !== '[') { | |
return [false, i]; | |
} | |
break; | |
} | |
} | |
if (stack.length === 0) { | |
return true; | |
} | |
return [false, stack.length - 1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment