Created
February 9, 2019 05:24
-
-
Save AndrewThian/01b2aba1133609ecf73d2c898d3575ea to your computer and use it in GitHub Desktop.
js challenge for asserting if brackets are balanced
This file contains hidden or 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 balanced(str) { | |
const stack = [] | |
let top; | |
for (let i = 0; i < str.length; i++) { | |
const char = str[i] | |
if (char === "(" || char === "{" || char === "[") { | |
console.log("pushing to stack") | |
stack.push(char) | |
} else { | |
if (stack.length === 0) { | |
console.log("stack empty") | |
return false | |
} | |
// else if current character does not match top of stack | |
switch(char) { | |
case "}": | |
console.log("checking }") | |
top = stack[stack.length - 1] | |
stack.pop() | |
if (top !== "{") { | |
console.log("no balance {") | |
return false | |
} | |
break; | |
case ")": | |
console.log("checking )") | |
top = stack[stack.length - 1] | |
stack.pop() | |
if (top !== "(") { | |
console.log("no balance (") | |
return false | |
} | |
break; | |
case "]": | |
console.log("checking ]") | |
top = stack[stack.length - 1] | |
stack.pop() | |
if (top !== "[") { | |
console.log("no balance [") | |
return false | |
} | |
break; | |
} | |
} | |
} | |
console.log("stack empty", stack.length === 0) | |
return stack.length === 0 | |
} | |
// console.log(balanced("[()]{}{[()()]()}")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment