遍历s ,并用一个栈来表示括号的深度。
遍历s ,并用一个栈来表示括号的深度。
遇到 ‘(’ 则将字符入栈,遇到 ‘)’ 则将栈顶字符出栈。栈从空到下一次空的过程,则是扫描了一个原语的过程。一个原语中,首字符和尾字符应该舍去,其他字符需放入结果字符串中。因此,在遇到 ‘(’ 并将字符入栈后,如果栈的深度为 1 ,则不把字符放入结果;在遇到 ‘)’ 并将栈顶字符出栈后,如果栈为空,则不把字符放入结果。
其他情况下,需要把字符放入结果。代码对流程进行了部分优化,减少了判断语句。
代码
Python3
class Solution: def removeOuterParentheses(self, s: str) -> str: res, stack = "", [] for c in s: if c == ')': stack.pop() if stack: res += c if c == '(': stack.append(c) return resC++
class Solution { public: string removeOuterParentheses(string s) { string res; stack<char> st; for (auto c : s) { if (c == ')') { st.pop(); } if (!st.empty()) { res.push_back(c); } if (c == '(') { st.emplace(c); } } return res; } };Java
class Solution { public String removeOuterParentheses(String s) { StringBuffer res = new StringBuffer(); Deque<Character> stack = new ArrayDeque<Character>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ')') { stack.pop(); } if (!stack.isEmpty()) { res.append(c); } if (c == '(') { stack.push(c); } } return res.toString(); } }复杂度分析
时间复杂度:O(n),其中 n 是输入 s 的长度。仅需遍历 s 一次。
空间复杂度:O(n),其中 n 是输入 s 的长度。需要使用栈,长度最大为 O(n)。
