Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created June 4, 2021 02:36
Show Gist options
  • Save CarlaTeo/9f5cb5a5a9ceb0796ae2f6a4bcc69aaa to your computer and use it in GitHub Desktop.
Save CarlaTeo/9f5cb5a5a9ceb0796ae2f6a4bcc69aaa to your computer and use it in GitHub Desktop.
[JS] Balanced brackets
const BRACKETS = {
"(": 1,
"[": 2,
"{": 3,
")": -1,
"]": -2,
"}": -3,
};
function isBalanced(s) {
const stack = [];
for(const bracket of s) {
const curBracketValue = BRACKETS[bracket];
if(curBracketValue > 0) stack.push(curBracketValue);
else {
const lastOpeningBracketValue = stack.pop();
if(curBracketValue + lastOpeningBracketValue !== 0) return false;
}
};
return stack.length ? false : true;
}
// ---------------------------- Test ----------------------------------//
console.log(isBalanced("")); // true
console.log(isBalanced("{[(])}")); // false
console.log(isBalanced("{{[[(())]]}}")); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment