LeetCode之Remove Outermost Parentheses(Kotlin)

问题:



方法:
遍历字符串,统计左括号和右括号的数量,当统计到左右括号数量相等时保存内部子串即去除了最外部的括号,遍历完成可得结果。

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))
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Remove Outermost Parentheses(Kotlin))