How to balance parenthesis recursively

后端 未结 9 1453
走了就别回头了
走了就别回头了 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条回答
  •  萌比男神i
    2021-02-01 00:36

    Adding to Vigneshwaran's answer (including comments & filtering unnecessary letters to avoid extra recursive calls):

    def balance(chars: List[Char]): Boolean = {
      @scala.annotation.tailrec
      def recurs_balance(chars: List[Char], openings: Int): Boolean = {
        if (chars.isEmpty) openings == 0
        else if (chars.head == '(') recurs_balance(chars.tail, openings + 1)
        else openings > 0 && recurs_balance(chars.tail, openings - 1)
      }
    
      recurs_balance(chars.filter(x => x == '(' || x == ')'), 0)
    }
    

提交回复
热议问题