Scala: Make sure braces are balanced

后端 未结 3 635
不思量自难忘°
不思量自难忘° 2021-01-19 07:54

I am running a code to balance brackets in statement. I think i have gotten it correct but it is failing on one particular statement, i need to understand why?

This

3条回答
  •  长情又很酷
    2021-01-19 08:19

    Here is a version:

    def balance(chars: List[Char]): Boolean = {
        def inner(c: List[Char], count: Int): Boolean = c match {
            case Nil                   => count == 0           // Line 1
            case ')' :: _ if count < 1 => false                // Line 2
            case ')' :: xs             => inner(xs, count - 1) // Line 3
            case '(' :: xs             => inner(xs, count + 1) // Line 4
            case _ :: xs               => inner(xs, count)     // Line 5
        }
        inner(chars, 0)
    }
    

    So in your code, I think you are missing the additional check for count < 1 when you encounter the right paranthesis! So you need an additional else if that checks for both the ')' and count < 1 (Line 2 in the example code above)

提交回复
热议问题