Skip to content

Instantly share code, notes, and snippets.

@AoiYamada
Created May 1, 2018 13:54
Show Gist options
  • Save AoiYamada/3107d8768834d2868a244726293d0a1b to your computer and use it in GitHub Desktop.
Save AoiYamada/3107d8768834d2868a244726293d0a1b to your computer and use it in GitHub Desktop.
check the given string is Brackets Balanced
function isBalanced(val) {
if(val.length) {
// strip off the nestest braces
const replaced_val = replaceBraces(val);
if(val === replaced_val)
return 'NO';
else
return isBalanced(replaced_val);
} else {
return 'YES';
}
}
function replaceBraces(val) {
// match all pairs of braces that have no nested braces
return val.replace(/\{(?:[^(:?\{.*?\}|\[.*?\]|\(.*?\))]|)+\}|\[(?:[^(:?\{.*?\}|\[.*?\]|\(.*?\))]|)+\]|\((?:[^(:?\{.*?\}|\[.*?\]|\(.*?\))]|)+\)/g, '');
}
// test
console.log(isBalanced('')); // YES
console.log(isBalanced('()[]{}')); // YES
consolele.log(isBalanced('([)[]')); // NO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment