Skip to content

Instantly share code, notes, and snippets.

@ccnixon
Created December 5, 2016 17:22
Show Gist options
  • Save ccnixon/45070925ce9d841ccf198c2435c272e2 to your computer and use it in GitHub Desktop.
Save ccnixon/45070925ce9d841ccf198c2435c272e2 to your computer and use it in GitHub Desktop.
Balanced Parens
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