Created
February 17, 2019 07:46
-
-
Save Vigowebs/20b4daeeaa4e9c399e48e61975e58a17 to your computer and use it in GitHub Desktop.
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 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