Skip to content

Instantly share code, notes, and snippets.

@Vigowebs
Created February 17, 2019 07:46
Show Gist options
  • Save Vigowebs/20b4daeeaa4e9c399e48e61975e58a17 to your computer and use it in GitHub Desktop.
Save Vigowebs/20b4daeeaa4e9c399e48e61975e58a17 to your computer and use it in GitHub Desktop.
function isBalanced(str) {
var i, ch;
var bracketsMap = new Map();
bracketsMap.set(']', '[');
bracketsMap.set('}', '{');
bracketsMap.set(')', '(');
// Use the spread operator to transform a map into a 2D key-value Array.
var closingBrackets = [...bracketsMap.keys()];
var openingBrackets = [...bracketsMap.values()];
var temp = [];
var len = str.length;
for (i = 0; i < len; i++) {
ch = str[i];
if (openingBrackets.indexOf(ch) > -1) {
temp.push(ch);
} else if (closingBrackets.indexOf(ch) > -1) {
var expectedBracket = bracketsMap.get(ch);
if (temp.length === 0 || (temp.pop() !== expectedBracket)) {
return false;
}
} else {
// Ignore the characters which do not match valid Brackets symbol
continue;
}
}
return (temp.length === 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment