Created
June 4, 2021 02:36
-
-
Save CarlaTeo/9f5cb5a5a9ceb0796ae2f6a4bcc69aaa to your computer and use it in GitHub Desktop.
[JS] Balanced brackets
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 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