我正在尝试学习scala并且正在做作业,但我无法弄清楚以下内容......
所以,问题是递归地判断括号是否平衡......递归。 所以这是我的工作解决方案..
def balance(chars: List[Char]): Boolean = {
def iterate(chars: List[Char], sum:Int):Int = {
if(chars.isEmpty || sum<0) sum
else if(chars.head == '(') iterate(chars.tail ,sum+1)
else if(chars.head == ')') iterate(chars.tail,sum-1)
else iterate(chars.tail, sum)
}
iterate(chars,0) == 0
}
但如果将我的代码更改为以下
def balance(chars: List[Char]): Boolean = {
def iterate(chars: List[Char], sum:Int):Int = {
if(chars.isEmpty || sum<0) sum
else if(chars.head == "(") iterate(chars.tail ,sum+1) //NOTE double quotes
else if(chars.head == ")") iterate(chars.tail,sum-1) //NOTE double quotes
else iterate(chars.tail, sum)
}
iterate(chars,0) == 0
}
这总是回归......
为什么?
//test with
val s1 = ":-)"
println(balance(s1.toList))
答案 0 :(得分:5)
chars.head是一个Char,'('是Char,但是“(”是一个字符串,所以这两个分支总是会变为假
else if(chars.head == "(") iterate(chars.tail ,sum+1) //NOTE double quotes
else if(chars.head == ")") iterate(chars.tail,sum-1) //NOTE double quotes
答案 1 :(得分:1)
使用匹配,您会看到错误:
<console>:11: error: type mismatch;
found : String("(")
required: Char
case "(" => loop(cs.tail, sum + 1)
^
使用更正后的代码:
def balance(cs: Seq[Char]) = {
def loop(cs: Seq[Char], sum: Int): Int = {
if (cs.isEmpty || sum < 0) sum
else {
val i = cs.head match {
case '(' => 1
case ')' => -1
case _ => 0
}
loop(cs.tail, sum + i)
}
}
loop(cs, 0) == 0
}