How to balance parenthesis recursively

后端 未结 9 1319
走了就别回头了
走了就别回头了 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:37

    It seems we are attending the same course. my solution:

    def balance(chars: List[Char]): Boolean = 
    doBalance(chars, 0) == 0;
    def doBalance(chars: List[Char], parenthesisOpenCount: Int): Int =
    if(parenthesisOpenCount <0) -100;
    else
    if(chars.isEmpty) parenthesisOpenCount
    else
      chars.head match {
      case '(' => return doBalance(chars.tail, parenthesisOpenCount+1) 
      case ')' => return doBalance(chars.tail, parenthesisOpenCount-1)
      case _ => return doBalance(chars.tail, parenthesisOpenCount)
    }
    

提交回复
热议问题