检查匹配括号的算法

时间:2014-05-05 17:17:43

标签: algorithm scala recursion

这与Coursera Scala课程有关,所以我想直接请你不要给我答案,而是帮我调试为什么会发生什么事情,因为直接答案会违反Coursera荣誉准则。< / p>

我有以下代码:

    def balance(chars: List[Char]): Boolean = {
    val x = 0
    def loop(list: List[Char]): Boolean = {
      println(list)

      if (list.isEmpty) if(x == 0) true
      else if (list.head == '(') pushToStack(list.tail)
      else if (list.head == ')') if(x <= 0) false else decreaseStack(list.tail)
      else loop(list.tail)


      true
    }

    def pushToStack(myList: List[Char]) { x + 1; loop(myList)}

    def decreaseStack(myList: List[Char]) { x - 1; loop(myList)}

    loop(chars)
  }

一个简单的解释:

如果代码看到“(”则它将变量加1。如果它看到“)”那么它首先检查变量是否等于或小于0.如果是这种情况,则返回false 。如果该值大于0,那么它只是从变量中减少一个。

我尝试过运行以下内容:

if(balance("This is surely bad :-( ) (".toList)) println("balanced") else println("not balanced");

显然这不平衡,但我的代码正在恢复平衡。

再说一遍:我不是在编写这个程序时请求帮助,而是帮助解释为什么当字符串不平衡时代码返回“平衡”

- 编辑 -

  def balance(chars: List[Char]): Boolean = {

    val temp = 0;

   def loop(list: List[Char], number: Int): Boolean = {
      println(list)

      if (list.isEmpty) if(number == 0) true
      else if (list.head == '(') loop(list.tail, number + 1)
      else if (list.head == ')') if(number <= 0) false else loop(list.tail, number - 1)
      else loop(list.tail,number)


      true
    }


    loop(chars,0)
  }

^^仍打印出平衡

2 个答案:

答案 0 :(得分:3)

当你真的想要一个可变的x时,你正在使用一个不可变的x

在这里,让我以尾递归的方式为你重写它,向你展示你实际在做什么:

@tailrec def loop(myList: List[Char], cur: Int = 0): Boolean = myList match{
  case "(" :: xs => 
    val tempINeverUse = cur+1
    loop(xs, cur) //I passed in 0 without ever changing "cur"!
  case ")" :: xs if cur < 0 => false //This is a bug, regardless if you fix the rest of it
  case ")" :: xs => 
    val tempINeverUse = cur-1
    loop(xs, cur) //Passed in 0 again!
  case x :: xs => loop(xs, cur)
  case Nil => cur == 0 //Since I've never changed it, it will be 0.
}

答案 1 :(得分:0)

您还需要在注释或引号中保留括号的上下文。您可以使用计数器来实现这一目标。如果计数器设置为注释或双引号,则忽略任何出现的括号。每当您找到完成评论或双引号时重置计数器

相关问题