How to balance parenthesis recursively

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

    My solution for this

    def balance(chars: List[Char]): Boolean = {
     var braceStack = new Stack[Char]()
    
    def scanItems(strList:List[Char]):Boolean = {
       if(strList.isEmpty)
           braceStack.isEmpty
       else{
          var item = strList.head
          item match {
            case '(' => braceStack.push(item)
                        scanItems(strList.tail)
            case ')'=> if(braceStack.isEmpty){
                            false
                        }
                        else {
                          braceStack.pop
                          scanItems(strList.tail)
                        }
            case _ => scanItems(strList.tail)
          }
        }
     }
    
     scanItems(chars)
    

    }

提交回复
热议问题