How to balance parenthesis recursively

后端 未结 9 1331
走了就别回头了
走了就别回头了 2021-01-31 23:56

I\'m working on some code to balance parenthesis, this question proved most useful for the algorithm.

I implemented it in my first language (PHP) but I\'m learning Scala

9条回答
  •  遇见更好的自我
    2021-02-01 00:38

    Same as Aaron Novstrup's answer but using 'if else'. I'm also attending the same course but we are taught upto if/else only so far.

    def balance(chars: List[Char]): Boolean = {
        def balanced(chars: List[Char], open: Int): Boolean = 
          if (chars.isEmpty) open == 0
          else if (chars.head == '(') balanced(chars.tail, open + 1)
          else if (chars.head == ')') open > 0 && balanced(chars.tail, open - 1)
          else balanced(chars.tail, open)
        balanced(chars, 0)
    }
    

提交回复
热议问题