-5

I got a assignment for balancing parentheses using scala. I wrote this code:

def balance(chars: List[Char]): Boolean = {

def check(sent: List[Char], count: Int): Int =
  if (sent.isEmpty)
    count
  else if (sent.head == '(')
    check(sent.tail, count + 1)
  else if (sent.head == ')')
    check(sent.tail, count - 1)
  else
    check(sent.tail, count)

     check(chars, 0) == 0 }

but this code fails in "())(" any idea to implement this code correct?

4

1 回答 1

5

Not giving any code away, just clarifying the likely spec. All your code is doing is counting the number of right and left parens, and making sure they are equal. That's a necessary condition, but not sufficient. For balanced parentheses, you also need to show that as you scan through the string, the number of '('s you have seen must always be greater than or equal to the number of ')'s seen.

于 2013-03-30T20:02:55.913 回答