Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

删除最外层的括号 #240

Open
louzhedong opened this issue Apr 18, 2021 · 0 comments
Open

删除最外层的括号 #240

louzhedong opened this issue Apr 18, 2021 · 0 comments

Comments

@louzhedong
Copy link
Owner

题目

有效括号字符串为空 ("")、"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"","()","(())()" 和 "(()(()))" 都是有效的括号字符串。

如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。

给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。

对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。

示例 1:

输入:"(()())(())"
输出:"()()()"
解释:
输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
示例 2:

输入:"(()())(())(()(()))"
输出:"()()()()(())"
解释:
输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
示例 3:

输入:"()()"
输出:""
解释:
输入字符串为 "()()",原语化分解得到 "()" + "()",
删除每个部分中的最外层括号后得到 "" + "" = ""。

提示:

S.length <= 10000
S[i] 为 "(" 或 ")"
S 是一个有效括号字符串

思路

如果使用栈的方式去思考,很容易进入死胡同

我们可以采用计数器的方式来求解

当我们遇到左括号时,计数器加一,遇到右括号时计数器减一。最终计数器的值肯定也为零

当遇到左括号,且计数器值大于0,则当前括号是有效的。当遇到右括号,且计数器值大于1,则当前括号是有效的

解答

/**
 * @param {string} S
 * @return {string}
 */
var removeOuterParentheses = function(S) {
    var res = "";
    var count = 0;
    for (var i = 0; i < S.length; i++) {
        if (S[i] == '(' && count++ > 0) {
             res += S[i];
        }
        if (S[i] == ')' && count-- > 1) {
            res += S[i];
        }
    }
    return res;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant