Last active
January 23, 2020 15:01
-
-
Save ngpestelos/5651977 to your computer and use it in GitHub Desktop.
Parentheses Balancing in Scala
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not covering below example:
"())"