Skip to content

Instantly share code, notes, and snippets.

@ngpestelos
Last active January 23, 2020 15:01
Show Gist options
  • Save ngpestelos/5651977 to your computer and use it in GitHub Desktop.
Save ngpestelos/5651977 to your computer and use it in GitHub Desktop.
Parentheses Balancing in Scala
def balance(chars: List[Char], open: Int): Boolean = {
if (chars.isEmpty)
open == 0
else if (chars.head == '(')
balance(chars.tail, open + 1)
else if (chars.head == ')' && open > 0)
// found an unmatched '(' earlier
balance(chars.tail, open - 1)
else
balance(chars.tail, open)
}
val x = "(x + y + (z + 1)))"
balance(x.toList, 0)
val y = "())("
balance(y.toList, 0)
@ppllaxxa
Copy link

It is not covering below example:
"())"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment