Basic Recursion, Check Balanced Parenthesis

前端 未结 12 1207
孤独总比滥情好
孤独总比滥情好 2020-11-29 17:56

I\'ve written software in the past that uses a stack to check for balanced equations, but now I\'m asked to write a similar algorithm recursively to check for properly neste

12条回答
  •  情深已故
    2020-11-29 18:12

    In the Scala programming language, I would do it like this:

      def balance(chars: List[Char]): Boolean = {
    
        def process(chars: List[Char], myStack: Stack[Char]): Boolean =
    
          if (chars.isEmpty) myStack.isEmpty
    
          else {
            chars.head match {
              case '(' => process(chars.tail, myStack.push(chars.head))
              case ')' => if (myStack.contains('(')) process(chars.tail, myStack.pop)
              else false
              case '[' => process(chars.tail, myStack.push(chars.head))
              case ']' => {
                if (myStack.contains('[')) process(chars.tail, myStack.pop) else false
              }
              case _ => process(chars.tail, myStack)
            }
          }
    
        val balancingAuxStack = new Stack[Char]
    
        process(chars, balancingAuxStack)
      }
    

    Please edit to make it perfect.

    I was only suggesting a conversion in Scala.

提交回复
热议问题