Skip to content

Instantly share code, notes, and snippets.

@mamalisk
Last active August 9, 2016 14:55
Show Gist options
  • Save mamalisk/f4a6212256b71950815876a45198fe47 to your computer and use it in GitHub Desktop.
Save mamalisk/f4a6212256b71950815876a45198fe47 to your computer and use it in GitHub Desktop.
Scala : Determine whether parentheses are balanced within a string
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