Created
June 29, 2015 23:33
-
-
Save Agnostic/d249be46ab4b781368d4 to your computer and use it in GitHub Desktop.
Is a string balanced? [Javascript]
This file contains hidden or 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 isBalanced(string) { | |
var balanced = true; | |
var parts = string.split(''); | |
var openBraces = /{|\[|\(/; | |
var closeBraces = /}|\]|\)/; | |
var stack = []; | |
for (var i = 0; i < parts.length; i++) { | |
if (parts[i].match(openBraces)) { | |
stack.push(parts[i]); | |
} else if (parts[i].match(closeBraces)) { | |
var lastChar = stack[stack.length - 1]; | |
if (parts[i] === '}' && lastChar !== '{') { | |
balanced = false; | |
} else if (parts[i] === ']' && lastChar !== '[') { | |
balanced = false; | |
} else if (parts[i] === ')' && lastChar !== '(') { | |
balanced = false; | |
} else { | |
stack.pop(); | |
} | |
} | |
} | |
return balanced; | |
} | |
isBalanced('{[()]}'); // => true | |
isBalanced('{[{}][()]}'); // => true | |
isBalanced('{]}'); // => false | |
isBalanced(')({}}'); // => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bug found!
You have to check whether the stack is empty at the end.