Created
June 19, 2017 14:52
-
-
Save rbobillot/cca4b6972e2ff11cf59e0278d659b5e2 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
object Solution extends App { | |
val expression = readLine.trim | |
val asso = Map(')' -> '(', ']' -> '[', '}' -> '{') | |
val isop = asso.values.toSet | |
val iscl = asso.keys.toSet | |
def cleanStack(c:Char)(implicit stack: List[Char]) = | |
stack.filter(_ == c).tail ++ stack.filterNot(_ == c) | |
def isBalanced(expr:List[Char])(implicit opened: List[Char] = Nil): Boolean = | |
expr match { | |
case o :: t if isop(o) => isBalanced(t)(expr.head::opened) | |
case c :: t if iscl(c) => if (!opened.contains(asso(c))) false else isBalanced(t)(cleanStack(asso(c))) | |
case h :: t => isBalanced(t) | |
case Nil => opened.isEmpty | |
} | |
println( isBalanced(expression.toList) ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment