括号平衡算法

时间:2016-09-30 09:45:27

标签: scala functional-programming

我正在使用scala中的一个小程序来检查某些表达式是否正确地形成了关于括号的打开和关闭。问题是here,但是我自己的程序。

def balance(chars: List[Char]): Boolean = {
  def balanced(chars: List[Char], opened: Int, closed: Int): Boolean = {
   if (chars.isEmpty && opened == closed) true
   else if (opened < closed) false
   else {
    if (chars.head == '(') balanced(chars.tail, opened + 1, closed)
    if (chars.head == ')') balanced(chars.tail, opened, closed + 1)
    else balanced(chars.tail, opened, closed)
   }
 }
  balanced(chars, 0, 0)

}

println(balance(“Just(some(random)sentence)。\ n(这不起作用)”。toList))

问题在于,例如它不适用于此示例。当我们从递归调用返回但我无法弄清楚错误是什么时,我跟踪了程序显然问题就出现了。

2 个答案:

答案 0 :(得分:2)

else {
    if (chars.head == '(') balanced(chars.tail, opened + 1, closed)
    if (chars.head == ')') balanced(chars.tail, opened, closed + 1)
    else balanced(chars.tail, opened, closed)
}

如果要将它们视为单个案例表达式,则有两个独立的if表达式。如果chars.head == '('true,则进行递归调用,但忽略结果,并评估第二个if。这将导致else分支被有效地忽略在第一个表达式中找到的(。您可以使用match例如

chars match {
  case Nil => opened == closed
  case '('::cs => balanced(cs, opened + 1, closed)
  case ')'::cs => balanced(cs, opened, closed + 1)
  case _::cs => balanced(cs, opened, closed)
}

答案 1 :(得分:0)

你可以尝试下面的代码可能是它的工作在上面的例子中也有问题,如果你有“sss”fff(“它也给出了真的所以它会在逻辑上错误

def balance(chars: List[Char]): Boolean = {
    def balrec(chars: List[Char], accr: Int, accl: Int): Boolean = {
      chars match {
        case head :: tail =>
          if (head.equals('(')) balrec(tail, accr + 1, accl)
          else if (head.equals(')') && (accr > accl || accr == 0)) balrec(tail, accr, accl + 1)
          else balrec(tail, accr, accl)
        case Nil => if (accr == accl) true else false
      }
    }

    balrec(chars, 0, 0)
  }