Created
May 16, 2022 12:03
-
-
Save guaiamum/2c54d70775c44a8b6961b9e249bd972a to your computer and use it in GitHub Desktop.
Exercise to check if string of brackets is balanced or nah..
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 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