虽然@jwvh 的回答解决了这个问题,但我的做法略有不同:
def squeeze(inputString: String, depth: Integer = 0): String = {
if (inputString.isEmpty) ""
else
inputString.head match {
case '(' => '(' + squeeze(inputString.tail, depth + 1)
case ')' if depth > 0 => ')' + squeeze(inputString.tail, depth - 1)
case ' ' if depth > 0 => squeeze(inputString.tail, depth)
case c : Char => c + squeeze(inputString.tail, depth)
}
}
这导致设计更加简洁,您可以使用默认参数,因此您不必向下传递元组。你也可以很容易地概括这一点:
def squeeze(inputString: String, depth: Integer = 0)
(remove: Char, replace: String)
(open: Char, close: Char)
: String = {
if (inputString.isEmpty) { "" }
else {
inputString.head match {
case `open` => open + squeeze(inputString.tail, depth + 1)(remove, replace)(open, close)
case `close` if depth > 0 =>
close + squeeze(inputString.tail, depth - 1)(remove, replace)(open, close)
case `remove` if depth > 0 =>
replace + squeeze(inputString.tail, depth)(remove, replace)(open, close)
case c : Char => c + squeeze(inputString.tail, depth)(remove, replace)(open, close)
}
}
}
val squeezeParen: (String) => (String) = squeeze(_)(' ', "")('(', ')')
val underscoreBracket: (String) => (String) = squeeze(_)(' ', "_")('[', ']')
正确性:
val a = "aaa bbb ccc ( 1 + 2 )"
val a_correct = "aaa bbb ccc (1+2)"
val b = "( 1 + 2 ) + ( 3 + 4 )"
val b_correct = "(1+2) + (3+4)"
val c = "[ a + 5 + ( 1 + 2)]"
val c_correct = "[ a + 5 + (1+2)]"
val c_alt = "[_a_+_5_+_(___1___+__2)]"
squeezeParen(a) == a_correct // true
squeezeParen(b) == b_correct // true
squeezeParen(c) == c_correct // true
underscoreBracket(c) == c_alt // true