How to balance parenthesis recursively

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

    You have mixed up the cases for ( and ).

    0 讨论(0)
  • 2021-02-01 00:45

    Just for completeness, I found an even more terse 'scala-esque' implementation from another SO question:

    def balance(chars: List[Char]): Boolean = chars.foldLeft(0){
      case (0, ')') => return false
      case (x, ')') => x - 1
      case (x, '(') => x + 1
      case (x, _  ) => x
    } == 0
    
    0 讨论(0)
  • 2021-02-01 00:46

    For what it's worth, here's a more idiomatic Scala implementation:

    def balance(chars: List[Char]): Boolean = {
      @tailrec def balanced(chars: List[Char], open: Int): Boolean = 
        chars match {
          case      Nil => open == 0
          case '(' :: t => balanced(t, open + 1)
          case ')' :: t => open > 0 && balanced(t, open - 1)
          case   _ :: t => balanced(t, open)
        }
    
      balanced(chars, 0)
    }
    
    0 讨论(0)
提交回复
热议问题