How to balance parenthesis recursively

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

    Instead of using Switch case you can use recursion to solve your problem in an efficient way.

    Following is my code to achieve the same with the help of recursion. You need to convert the string to List for my method.

    Code :

    object Balance {
    
      def main(args: Array[String]): Unit = {
        var paranthesis = "(234(3(2)s)d)" // Use your string here
        println(bal(paranthesis.toList)) // converting the string to List 
      }
    
      def bal(chars: List[Char]): Boolean ={
       // var check  = 0
        def fun(chars: List[Char],numOfOpenParan: Int): Boolean = {
          if(chars.isEmpty){
            numOfOpenParan == 0
          }
          else{
            val h = chars.head
    
            val n = 
              if(h == '(') numOfOpenParan + 1
              else if (h == ')') numOfOpenParan - 1
              else numOfOpenParan 
    
           // check  = check + n
            if (n >= 0) fun(chars.tail,n)
            else false 
          }
        }
        fun(chars,0)
      }
    }
    

提交回复
热议问题