Created
May 1, 2018 13:54
-
-
Save AoiYamada/3107d8768834d2868a244726293d0a1b to your computer and use it in GitHub Desktop.
check the given string is Brackets 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
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