Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Created June 19, 2017 14:52
Show Gist options
  • Save rbobillot/cca4b6972e2ff11cf59e0278d659b5e2 to your computer and use it in GitHub Desktop.
Save rbobillot/cca4b6972e2ff11cf59e0278d659b5e2 to your computer and use it in GitHub Desktop.
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