Last active
August 9, 2016 14:55
-
-
Save mamalisk/f4a6212256b71950815876a45198fe47 to your computer and use it in GitHub Desktop.
Scala : Determine whether parentheses are balanced within a string
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]): Boolean = { | |
val onlyBrackets = chars.filter(c => '('.equals(c) || ')'.equals(c)) | |
@tailrec | |
def isBalanced(status : Int, chars : List[Char]) : Boolean = { | |
if(chars.isEmpty) status == 0 | |
else status >= 0 && isBalanced({if(chars.head == ')') status - 1 else status + 1}, chars.tail) | |
} | |
onlyBrackets.size % 2 == 0 && isBalanced(0,onlyBrackets) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment