Created
September 22, 2014 15:59
-
-
Save rewonc/14168523a30a672b09bf to your computer and use it in GitHub Desktop.
Checking whether parentheses balance each other in Scala
This file contains hidden or 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 = { | |
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