Created
March 28, 2013 13:21
-
-
Save vkobel/5263080 to your computer and use it in GitHub Desktop.
Simple parentheses balancing method using tailrec
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
package week1 | |
import scala.annotation.tailrec | |
object parenthesesBalancing { | |
def balance(chars: List[Char]): Boolean = { | |
def analyse(c: Char) = | |
if (c == '(') 1 | |
else if (c == ')') -1 | |
else 0 | |
@tailrec | |
def loop(cnt: Int, chars: List[Char]): Boolean = { | |
if (cnt < 0) false | |
else if (chars.isEmpty && cnt == 0) true | |
else if (chars.isEmpty && cnt != 0) false | |
else loop(cnt + analyse(chars.head), chars.tail) | |
} | |
loop(0, chars) | |
} //> balance: (chars: List[Char])Boolean | |
balance("((()()".toList) //> res0: Boolean = false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment