Created
January 12, 2020 23:18
-
-
Save mathew-fleisch/1f499602f96af01b2af9cd71c253ee69 to your computer and use it in GitHub Desktop.
Balanced Parentheses
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
matrix = [["(","("],[")",")"]] | |
matrix1 = [["(","("],["(",")"]] | |
matrix2 = [["(",")"],[")",")"]] | |
matrix3 = [["(",")"],["(",")"]] | |
console.log(`isBalanced(${JSON.stringify(matrix)}) => ${isBalanced(matrix)}`) | |
console.log(`isBalanced(${JSON.stringify(matrix1)}) => ${isBalanced(matrix1)}`) | |
console.log(`isBalanced(${JSON.stringify(matrix2)}) => ${isBalanced(matrix2)}`) | |
console.log(`isBalanced(${JSON.stringify(matrix3)}) => ${isBalanced(matrix3)}`) | |
function isBalanced(matrix) { | |
balancedStack = [] | |
for (let x = 0; x < matrix.length; x++){ | |
for (let y = 0; y < matrix[x].length; y++){ | |
switch (matrix[x][y]) { | |
case "(": | |
balancedStack.push("(") | |
break | |
case ")": | |
if (balancedStack.length === 0) | |
return false | |
balancedStack.pop() | |
} | |
} | |
} | |
if (balancedStack.length === 0) { | |
for (let y = 0; y < matrix[0].length; y++){ | |
for (let x = 0; x < matrix.length; x++){ | |
switch (matrix[x][y]) { | |
case "(": | |
balancedStack.push("(") | |
break | |
case ")": | |
if (balancedStack.length === 0) | |
return false | |
balancedStack.pop() | |
} | |
} | |
} | |
} | |
return (balancedStack.length === 0 ? true : false) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment