Skip to content

Instantly share code, notes, and snippets.

@evandocarmo
Created August 14, 2017 02:21
Show Gist options
  • Save evandocarmo/a75e4e4d21c4c16d383ba60265112059 to your computer and use it in GitHub Desktop.
Save evandocarmo/a75e4e4d21c4c16d383ba60265112059 to your computer and use it in GitHub Desktop.
var closingMap = {
'{': '}',
'[': ']',
'(': ')'
};
function isBalancedBracketSequence(expression) {
var length = expression.length;
if (length <= 1 || length % 2 !== 0) {
return false;
}
var stack = []; //represents the bracket level. Should be zero at the end of a balanced bracket sequence
var expression = expression.split('');
for (var i = 0; i < expression.length; i++) { //for each bracket, test if it's opening or closing
var bracket = expression[i];
if (closingMap[bracket]) { //if it's opening...
stack.push(closingMap[bracket]); //push it into the stack. We owe one closing bracket
} else { //if it's a closing bracket, we have to pop it from the stack
if (stack.length === 0 || stack[stack.length - 1] !== bracket)
return false; // BUT if the stack is zeroed or is not the same type, it's unmatched
stack.pop();
}
}
if (stack.length) //if there's something left in the stack, it's unmatched
return false;
else
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment