Created
December 5, 2016 17:22
-
-
Save ccnixon/45070925ce9d841ccf198c2435c272e2 to your computer and use it in GitHub Desktop.
Balanced Parens
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
var test = '{[()]}'; | |
function balancedParens(str) { | |
var parens = { | |
'{': '}', | |
'[': ']', | |
'(': ')' | |
} | |
var stack = [] | |
for (var i = 0; i < str.length; i++) { | |
// Check if i is an opener and push onto stack | |
if (parens[str[i]]) | |
{ | |
stack.push(str[i]); | |
} | |
/** | |
* If it's a closing paren, pop off the last known opener, | |
* check to ensure the stack is not empty, then ensure it | |
* corresponds to the correct closer. | |
*/ | |
else | |
{ | |
var opener = stack.pop(); | |
if (!opener) return false; | |
if (parens[opener] != str[i]) return false; | |
} | |
} | |
return stack.length === 0; | |
} | |
console.log(balancedParens(test)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment