Skip to content

Instantly share code, notes, and snippets.

@SharpCoder
Last active February 3, 2017 01:40
Show Gist options
  • Select an option

  • Save SharpCoder/313303982381933e686f90f7098e86ea to your computer and use it in GitHub Desktop.

Select an option

Save SharpCoder/313303982381933e686f90f7098e86ea to your computer and use it in GitHub Desktop.
Balanced parenthesis problem
var open = ["(", "{", "["];
var closed = [")", "}", "]"];
function isMatched(str) {
var stack = [];
if (str === null || str === undefined) return false;
if (str.length == 1 ) return false;
for (var i = 0; i < str.length; i++) {
var character = str[i];
var openIndex = open.indexOf(character);
var closedIndex = closed.indexOf(character);
if (openIndex >= 0) {
stack.push(character);
} else if (closedIndex >= 0){
var match = open[closedIndex];
if (stack.pop() != match) {
return false;
}
} else {
// Determine what to do here.
// Ask if we should consider non parenthesies as
// a failure state or ignore them.
return false;
}
}
// If we have all open or all closed, this will catch
// that state.
return stack.length == 0;
}
console.log(isMatched("[{({})}]"));
console.log(isMatched("[[{{({)}}]]"));
console.log(isMatched("("));
console.log(isMatched("(("));
console.log(isMatched("(A)"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment