【发布时间】:2016-08-31 05:55:49
【问题描述】:
我正在学习 Scala 并编写一个函数(递归)来计算括号的数量:+1 表示打开,-1 表示关闭,以便匹配和平衡字符列表中的所有括号。如果括号是平衡的,它应该返回 0。
我想出了这个(用大量的打印语句来理解发生了什么):
def countPar(charList: List[Char], count: Int): Int = {
if (count < 0) {
println("negative count, returning", count)
count
}
else if (charList.isEmpty) {
println("empty list, returning", count)
count
}
else if (charList.head.equals('(')) {
println("head is ", charList.head, " count + 1:", count + 1)
count + countPar(charList.tail, count + 1)
}
else if (charList.head.equals(')')) {
println("head is ", charList.head, " count - 1:", count - 1)
count + countPar(charList.tail, count - 1)
}
else {
println("head is ", charList.head, " count:", count)
countPar(charList.tail, count)
}
}
val parCount = countPar("(a(b)c)".toList, 0)
println(parCount)
打印语句做似乎证实了逻辑是有效的,但最终的返回值是错误的:
(head is ,(, count + 1:,1)
(head is ,a, count:,1)
(head is ,(, count + 1:,2)
(head is ,b, count:,2)
(head is ,), count - 1:,1)
(head is ,c, count:,1)
(head is ,), count - 1:,0)
(empty list, returning,0)
parCount: Int = 4
我错过了什么?
【问题讨论】:
-
为什么
count +在几个递归的情况下? -
我正在跟踪括号的数量并将其作为参数传递。 +1 开头,-1 结尾。
-
想想递归调用应该返回什么。你确定
count +没有重复计算吗? -
但现在我明白你的意思了......没有理由,这就是问题所在