# 1021.Remove Outermost Parentheses

**1021.Remove Outermost Parentheses**

难度:Easy

> 有效括号字符串为空 ("")、"(" + 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 是一个有效括号字符串
```

解法，用栈判断，然后去除最外层括号：

```
class Solution {
public:
    string removeOuterParentheses(string S) {
        if(S=="") return S;
        stack<char> pri;
        string res;
        int flag=0;
        for(char c :S)
        {

            if(c=='(')
            {
                if(!pri.empty() || flag)
                {
                    pri.push(c);
                    res+=c;
                }
                else
                    flag=1;
            }
                
            else if(c==')')
            {
                if(pri.empty())
                    flag=0;
                else
                {
                    res+=c;
                    pri.pop();
            }
            }

        //    cout<<pri.size()<<endl;
        }
        return res;
    }
};
```

> 执行用时 : 12 ms, 在Remove Outermost Parentheses的C++提交中击败了83.57% 的用户 内存消耗 : 9.1 MB, 在Remove Outermost Parentheses的C++提交中击败了45.88% 的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/1021.remove_outermost_parentheses.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
