Skip to content

Instantly share code, notes, and snippets.

@burkov
Last active July 16, 2017 21:46
Show Gist options
  • Save burkov/0d2ad3c079e04629e3796aa6815dae67 to your computer and use it in GitHub Desktop.
Save burkov/0d2ad3c079e04629e3796aa6815dae67 to your computer and use it in GitHub Desktop.
private val openingBrackets = "([{<"
private val closingBrackets = ")]}>"
fun String.isBalancedComplex(): Boolean =
fold(Stack<Char>()) { acc, c ->
when (c) {
// For kotlin beginners: `apply(..)` == `{acc.push(c); acc}`: just a shorthand to eliminate 1 line of code, nothing fancy here
in openingBrackets -> acc.apply { push(c) }
in closingBrackets -> {
if (acc.isEmpty()) return false // leading closing braket like ')))'
val last = acc.pop()
val doesntMatch = closingBrackets.indexOf(c) != openingBrackets.indexOf(last) // inefficient but brief
if (doesntMatch) return false
else acc
}
else -> acc // do nothing its an non-bracket symbol
}
}.isEmpty()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment