我已经实现了一种递归方法来检查字符串中括号的数目是否有效。这是代码
def balance(chars: List[Char]): Boolean = {
@tailrec
def isValid(newChars: List[Char], difference: Int): Boolean = {
if (newChars.isEmpty) difference == 0
else if (difference < 0) false
else {
var newDifference = difference // Scala IDE gives warning here
if (newChars.head == '(') newDifference = difference + 1
else if (newChars.head == ')') newDifference = difference - 1
isValid(newChars.tail, newDifference)
}
}
isValid(chars, 0)
}
我在以下测试案例中测试了上面的代码,它工作正常,所以我只是在寻找改进if / else阶梯的方法。
println("Testing parenthesis balancing")
assert(balance("(Sachin is learning (scala) and (spark))".toList))
assert(!balance("(Invalid))(expression)".toList))
assert(balance("".toList))
assert(balance("()()".toList))
assert(!balance("{())}{()}".toList))
如代码中所述,Scala IDE在该行抱怨说
避免可变的局部变量
我不太确定如何在newDifference
不使用if / else的情况下计算的值。我可以看到的其他选项是isValid
在if / else阶梯中直接使用newDifference的计算值调用方法。
我仍在学习Scala,所以我想知道在不改变局部变量(或任何其他警告)的情况下编写此代码的最佳方法。
你可以写:
val newDifference =
if (newChars.head == '(') difference + 1
else if (newChars.head == ')') difference - 1
else difference;
如if
在Scala中是一个表达式或use match
,在这种情况下,它被认为更惯用:
val newDifference = newChars.head match {
case '(' => difference + 1
case ')' => difference - 1
case _ => difference
}
整个函数可以转换成一个match
on newChars
,但我将留给您。有关一些想法,请参见此处的第一个示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句