我正在使用scala和recursion为括号平衡构建一个小方法。
我出来了这个代码,令人惊讶地无效。
object Test{
def balance(chars: List[Char]): Boolean=
{
var opening_index: Int = -1
var closing_index: Int = -1
opening_index = chars.indexOf('(')
closing_index = chars.indexOf(')')
println(opening_index)
println(closing_index)
if ( chars.size == 0 ) true
if ((opening_index == -1) & (closing_index== -1))
{
true
}
if (closing_index> -1 & opening_index> -1)
{
if (closing_index< opening_index) return(false)
else
{
balance(chars.filter(_!=chars(closing_index)).filter(_!=chars(opening_index)))
}
}
else
return (false)
}
val lst:List[Char] = List('(',')' ,'3','4')
balance(lst)
}
我知道还有其他类似的帖子,但我比其他人更感兴趣使用这种方法。
答案 0 :(得分:0)
此代码存在两个主要(功能)问题。
首先,此测试不执行任何操作,因为结果被丢弃
if ((opening_index == -1) & (closing_index== -1))
{
true
}
你可能意味着return true
其次,递归调用是错误的
balance(chars.filter(_ != chars(closing_index)).filter(_ != chars(opening_index)))
对filter
的这两次调用正在从列表中删除 所有 括号,因此对balance
的调用将始终成功,即使列表的其余部分是不平衡的。
您可能希望使用三次slice
调用来删除opening_index
和closing_index
处的特定括号。
答案 1 :(得分:0)
您可以使用以下解决方案检查余额括号。
object Driver extends App{
def balance(chars: List[Char]): Boolean=
{
if (chars.mkString("").length() == 0) {
return true;
}
if (chars.mkString("").contains("()")) {
return balance(chars.mkString("").replaceFirst("\\(\\)", "").toCharArray.toList);
}
if (chars.mkString("").contains("[]")) {
return balance(chars.mkString("").replaceFirst("\\[\\]", "").toCharArray.toList);
}
if (chars.mkString("").contains("{}")) {
return balance(chars.mkString("").replaceFirst("\\{\\}", "").toCharArray.toList);
} else {
return false;
}
}
println(balance(List('(','{','}')))
println(balance(List('(','{','}',')')))
}
答案 2 :(得分:0)
您可能希望按索引进行过滤,而不是按字符进行过滤。实际上,您的代码会删除第一轮中的所有括号。
此处与zipWithIndex
一起使用,并将索引与opening_index
和closing_index
进行比较:
def balance(chars: List[Char]): Boolean = {
val opening_index = chars.indexOf('(')
val closing_index = chars.indexOf(')')
if ( chars.size == 0 ) {
true
} else if ((opening_index == -1) && (closing_index== -1)) {
true
} else if (closing_index > -1 && opening_index > -1) {
if (closing_index < opening_index) {
false
} else {
balance(
chars.zipWithIndex.filterNot{
case (c, i) => i == opening_index || i == closing_index
}.map(_._1)
)
}
} else {
false
}
}
println(balance("()34".toList))
println(balance("()34)".toList))
println(balance("(x)(y(z))".toList))
println(balance("(x)(y(z)".toList))
输出:
true
false
true
false