Skip to content

Instantly share code, notes, and snippets.

@vkobel
Created March 28, 2013 13:21
Show Gist options
  • Save vkobel/5263080 to your computer and use it in GitHub Desktop.
Save vkobel/5263080 to your computer and use it in GitHub Desktop.
Simple parentheses balancing method using tailrec
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