A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.  For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

 

Example 1:

Input: "(()())(())"
Output: "()()()"
Explanation: 
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:

Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation: 
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:

Input: "()()"
Output: ""
Explanation: 
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
 

Note:

S.length <= 10000
S[i] is "(" or ")"
S is a valid parentheses string

这题让我们去掉最外层的括号,所以我们扫描整个字符串,扫描到第一个或者最后一个,不放入结果字符串即可。

class RemoveOutermostParentheses : public Solution {
    public:
    void Exec() {
        cout << "Case 1: " << removeOuterParentheses("(()())(())") << std::endl;
    }

    string removeOuterParentheses(string S) {
        int count = 0;
        string res;
        res.reserve(S.size());

        for (int i = 0; i < S.size(); i++) {
            if (S[i] == '(') {
                count++;
                if (count > 1) {
                    res.push_back(S[i]);
                }
            } else if (S[i] == ')') {
                count--;
                if (count > 0) {
                    res.push_back(S[i]);
                }
            }
        }
        return res;
    }
};

共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day