Skip to content

Instantly share code, notes, and snippets.

@garciamax
Created May 19, 2016 12:42
Show Gist options
  • Save garciamax/b460915ca1f2026bd6f434cf47f50756 to your computer and use it in GitHub Desktop.
Save garciamax/b460915ca1f2026bd6f434cf47f50756 to your computer and use it in GitHub Desktop.
Solve matching parentheses problem.
var results = new Array();
var l = console.log.bind(console)
//Task
results.push(verify("---(++++)----"));// -> true
results.push(verify(""));// -> true
results.push(verify("before ( middle []) after "));// -> false
results.push(verify(") ("));// -> false
results.push(verify("} {"));// -> true
results.push(verify("<(   >)"));// -> false
results.push(verify("(  [  <>  ()  ]  <>  )"));// -> true
results.push(verify("   (      [)"));// -> false
if(JSON.stringify(results) === JSON.stringify([true, true, true, false, true, false, true, false]){
l('Success!')
}else{
l('Fail!')
}
//Solution
function verify(str){
stack = []
opening = ['<', '[', '(']
closing = ['>', ']', ')']
pairs = {'>':'<', ']':'[', ')':'('}
for(var i = 0, len = str.length; i < len; i++){
if(opening.indexOf(str[i]) > -1) {
stack.push(str[i])
}else if(closing.indexOf(str[i]) > -1){
if(stack.length === 0) return false;
translatedCh = pairs[str[i]]
stackTop = stack[stack.length-1]
if (stackTop === translatedCh){
stack.pop()
}else{
return false
}
}
}
return stack.length === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment