我将尝试对@jonderry 的回答进行更详细的解释。代码优先,在 Scala 中
def parBalance(chars: Array[Char], chunkSize: Int): Boolean = {
require(chunkSize > 0, "chunkSize must be greater than 0")
def traverse(from: Int, until: Int): (Int, Int) = {
var count = 0
var stack = 0
var nest = 0
for (n <- from until until) {
val cur = chars(c)
if (cur == '(') {
count += 1
stack += 1
}
else if (cur == ')') {
count -= 1
if (stack > 0) stack -= 1
else nest -= 1
}
}
(nest, count)
}
def reduce(from: Int, until: Int): (Int, Int) = {
val m = (until + from) / 2
if (until - from <= chunkSize) {
traverse(from, until)
} else {
parallel(reduce(from, m), reduce(m, until)) match {
case ((minNestL, totGainL), (minNestR, totGainR)) => {
((minNestL min (minNestR + totGainL)), (totGainL + totGainR))
}
}
}
}
reduce(0, chars.length) == (0,0)
}
给定一个字符串,如果我们删除平衡括号,剩下的将是 )))((( 的形式,给 ) 的数字 n 和数字 m (,然后 m >= 0,n n 是 minNest 而 m+n 是 totGain。要制作真正平衡的琴弦,我们需要m+n == 0 && n == 0。
在并行操作中,我们如何从它的左右推导出节点?对于 totGain,我们只需要将它们相加。在计算节点的 n 时,如果 n(right) 没有贡献,它可以只是 n(left) 或 n(right) + left.totGain 中较小的一个。