Skip to content

Instantly share code, notes, and snippets.

@rewonc
Created September 22, 2014 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rewonc/14168523a30a672b09bf to your computer and use it in GitHub Desktop.
Save rewonc/14168523a30a672b09bf to your computer and use it in GitHub Desktop.
Checking whether parentheses balance each other in Scala
def balance(chars: List[Char]): Boolean = {
def balIter(chars: List[Char], count: Int): Boolean = {
if (chars.isEmpty){
if (count == 0) true else false
} else{
if (chars.head.toString == ")") {
if (count < 1) false else balIter(chars.tail, count - 1)
} else if (chars.head.toString == "("){
balIter(chars.tail, count + 1)
} else {
balIter(chars.tail, count)
}
}
}
balIter(chars, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment