Skip to content

Instantly share code, notes, and snippets.

@guaiamum
Created May 16, 2022 12:03
Show Gist options
  • Save guaiamum/2c54d70775c44a8b6961b9e249bd972a to your computer and use it in GitHub Desktop.
Save guaiamum/2c54d70775c44a8b6961b9e249bd972a to your computer and use it in GitHub Desktop.
Exercise to check if string of brackets is balanced or nah..
const isBalanced = (s) => {
const stack = [];
const charArray = s.split("");
for (const [index, char] of charArray.entries()) {
switch (char) {
// insert
case "(":
case "[":
case "{":
stack.push(char);
break;
// remove (
case ")": {
const last = stack.pop();
if (last !== "(") {
return false;
}
break;
}
// remove [
case "]": {
const last = stack.pop();
if (last !== "[") {
return false;
}
break;
}
// remove {
case "}": {
const last = stack.pop();
if (last !== "{") {
return false;
}
break;
}
default:
break;
}
}
return !stack.length;
};
const testCases = [
"())", // false
"(())", // true
"{[(])}", // false
"{[()]}", //true
"{[()[]]}", //true
];
for(const test of testCases){
console.log(`is "${test}" balanced?: `, isBalanced(test) ? 'yes' : 'no');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment