问题:
方法: 遍历字符串,统计左括号和右括号的数量,当统计到左右括号数量相等时保存内部子串即去除了最外部的括号,遍历完成可得结果。
package com.eric.leetcode
class RemoveOutermostParentheses {
fun removeOuterParentheses(S: String): String {
var start = 0
var left = 0
var right = 0
val result = StringBuilder()
for (index in S.indices) {
if (S[index] == '(') {
left++
} else {
right++
}
if (left == right) {
result.append(S.subSequence(start + 1, index))
start = index + 1
}
}
return result.toString();
}
}
fun main() {
val input = "()()"
val removeOutermostParentheses = RemoveOutermostParentheses()
print(removeOutermostParentheses.removeOuterParentheses(input))
}
有问题随时沟通