def balance(chars: List[Char]): Boolean = {
if (chars.isEmpty == true) true
else transCount(chars, 0)
def transCount(chars: List[Char], pro: Int): Boolean = {
var dif = pro
chars match {
case "(" :: Nil => false
case ")" :: Nil => dif -= 1; if (dif == 0) true else false
case _ :: Nil => if (dif == 0) true else false
case "(" :: tail => dif += 1
transCount(tail, dif)
case ")" :: tail => dif -= 1;
if (dif < 0) false
else transCount(tail, dif)
case _ :: tail => transCount(tail, dif)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有类型不匹配的问题
Error:(30, 13) type mismatch;
found : String("(")
required: Char
case "(" :: Nil => false
^
Run Code Online (Sandbox Code Playgroud)
但真的不知道如何修复(请不要使用char.toList请)
chars被宣布为List[Char].
但是,你的第一个模式是"(" :: Nil,List[String]因为"("是一个字符串 - 因此类型不匹配.
您需要一个字符文字'(',而不是字符串文字"("
当然,这同样适用于其他模式.
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |