Created
November 27, 2021 12:23
-
-
Save QuatoHub/85f3ca715ec35ef9868633567de8168e to your computer and use it in GitHub Desktop.
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
// naive solution | |
const balancedBrackets = function (str) { | |
const stack = []; | |
const opener = '('; | |
const closer = ')'; | |
for (let i = 0; i < str.length; i++) { | |
if (str[i] === opener) { | |
stack.push(str[i]); | |
} else if (str[i] === closer) { | |
const top = stack.pop(); | |
if (top !== opener) { | |
return false; | |
} | |
} | |
} | |
return stack.length === 0; | |
}; | |
// Advanced solution | |
const balancedBrackets = function (str) { | |
const stack = []; | |
const opener = { | |
'{': '}', | |
'[': ']', | |
'(': ')', | |
}; | |
const closer = '}])'; | |
for (let i = 0; i < str.length; i++) { | |
if (str[i] in opener) { | |
stack.push(str[i]); | |
} else if (closer.includes(str[i])) { | |
const top = stack.pop(); | |
const pair = opener[top]; | |
if (pair !== str[i]) { | |
return false; | |
} | |
} | |
} | |
return stack.length === 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment