Created
February 12, 2014 18:55
-
-
Save apkostka/8962097 to your computer and use it in GitHub Desktop.
Algorithm to determine if brackets are balanced in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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