How to balance parenthesis recursively

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

      val myStack = new Stack[Char]
    
      def balance(chars: List[Char]): Boolean = {
        def processParanthesis(x: Char, a: List[Char]): Stack[Char] = {
          if (x == '(') {
            myStack.push('(');
          } else if (x == ')') {
            if (!myStack.empty())
              myStack.pop();
            else
              myStack.push(')');
          }
          if (a.length == 0)
            return myStack;
          else
            return processParanthesis(a.head, a.tail);
        }
        return processParanthesis(chars.head, chars.tail).empty();
      }
    

提交回复
热议问题