Skip to content

Instantly share code, notes, and snippets.

@Agnostic
Created June 29, 2015 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Agnostic/d249be46ab4b781368d4 to your computer and use it in GitHub Desktop.
Save Agnostic/d249be46ab4b781368d4 to your computer and use it in GitHub Desktop.
Is a string balanced? [Javascript]
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
@arcesino
Copy link

arcesino commented Jul 2, 2015

Bug found!

isBalanced('{{}'); // => Returns true but should be false

You have to check whether the stack is empty at the end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment