Last active
July 16, 2017 21:46
-
-
Save burkov/0d2ad3c079e04629e3796aa6815dae67 to your computer and use it in GitHub Desktop.
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
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