Skip to content

Instantly share code, notes, and snippets.

@ufocoder
Created November 23, 2018 11:13
Show Gist options
  • Select an option

  • Save ufocoder/e78700221a5f251b6beeef294048f565 to your computer and use it in GitHub Desktop.

Select an option

Save ufocoder/e78700221a5f251b6beeef294048f565 to your computer and use it in GitHub Desktop.
const bracketList = '[]{}()'
const bracketNumber = bracketList.length / 2
const hasBalancedBrackets = str => {
const stack = []
let bracketOpenLastIndex = null
let bracketOpenIndex = null
let bracketCloseIndex = null
for (let bi = 0; bi < bracketNumber; bi++) {
bracketOpenIndex = bi * 2
bracketCloseIndex = bi * 2 + 1
for (let si = 0; si < str.length; si++) {
if (str[si] == bracketList[bracketOpenIndex]) {
stack.push(bracketOpenIndex)
bracketOpenLastIndex = bracketOpenIndex
}
if (str[si] == bracketList[bracketCloseIndex]) {
if (bracketOpenLastIndex !== bracketOpenIndex || !stack.length) {
return false
}
stack.pop()
bracketOpenLastIndex = stack[stack.length - 1]
}
}
}
return !stack.length;
}
const testCases = {
positive: ['', '_', '[_]', '{_}', '[_{_}_]', '[_(_{_}_)_]'],
negative: ['[', '[{]', '[{[{]}]']
}
testCases.positive.forEach(testCase => console.assert(hasBalancedBrackets(testCase)))
testCases.negative.forEach(testCase => !console.assert(!hasBalancedBrackets(testCase)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment