Last active
July 24, 2017 14:43
-
-
Save vacas/adee711286c16b0e41eb747bd4b73de8 to your computer and use it in GitHub Desktop.
Learning about Data Structures (Stacks) using Hacker Rank exercise - Balanced Brackets
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
// Cleaner implementation without Stacks, but using its concept | |
function main(arr) { | |
var solution = [], | |
balanced = true; | |
for (var i = 0; i < arr.length; i++){ | |
switch(arr[i]){ | |
case '{': | |
case '(': | |
case '[': | |
solution.push(arr[i]); | |
break; | |
default: | |
if(solution.length === 0 || !checkBalanced(solution.pop(), arr[i])){ | |
balanced = false; | |
} | |
break; | |
} | |
} | |
if(balanced && solution.length === 0){ | |
return 'YES'; | |
} else { | |
return 'NO'; | |
} | |
} | |
function checkBalanced(first, second){ | |
var pair = [ | |
['[', ']'], | |
['{', '}'], | |
['(', ')'] | |
]; | |
for(var i = 0; i < pair.length; i++){ | |
if(pair[i][0] === first && pair[i][1] === second){ | |
return true; | |
} | |
} | |
return false; | |
} | |
console.log(main('[{[{})[][[}{}]]]}]}]')); | |
console.log(main('[][](){{[{()}]}}{}([])')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment