Skip to content

Instantly share code, notes, and snippets.

@kharandziuk
Created July 4, 2019 12:00
Show Gist options
  • Select an option

  • Save kharandziuk/d1dc4c0545bb66d6f5c17685cc144f25 to your computer and use it in GitHub Desktop.

Select an option

Save kharandziuk/d1dc4c0545bb66d6f5c17685cc144f25 to your computer and use it in GitHub Desktop.
function isBalanced(str) {
const stack = str.split('')
const compare = []
while(stack.length) {
//console.log(stack, compare)
let current = stack.shift();
if(compare.length == 0) {
compare.push(current)
} else {
if(compare[compare.length - 1] === '(' && current === ')') {
compare.pop()
} else {
compare.push(current)
}
}
}
return compare.length === 0
}
console.log(isBalanced('()') === true)
console.log(isBalanced('(') === false)
console.log(isBalanced(')') === false)
console.log(isBalanced('()()') === true)
console.log(isBalanced('())(') === false)
console.log(isBalanced(')(') === false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment