Skip to content

Instantly share code, notes, and snippets.

@apkostka
Created February 12, 2014 18:55
Show Gist options
  • Save apkostka/8962097 to your computer and use it in GitHub Desktop.
Save apkostka/8962097 to your computer and use it in GitHub Desktop.
Algorithm to determine if brackets are balanced in a string
function balanced(str){
var opens = ['{','(','['],
closes = ['}',')',']'],
split = str.split(''),
stack = [];
for (var i = 0; i < split.length - 1; i++){
if (opens.indexOf(split[i]) >= 0){
stack.push(split[i]);
} else if (closes.indexOf(split[i]) >= 0) {
var pop = stack.pop();
if (opens.indexOf(pop) !== closes.indexOf(split[i]) || stack.length == 0){
return false;
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment