解题思路:
一道非常简单的栈应用题,遇到左括号入栈,右括号出栈,栈空即找到一个原语的一部分,取出最外面两个括号加入到字符串中,代码如下:
class Solution {
public:
string removeOuterParentheses(string s) {
stack<char> st;
string res;
int i = 0;
while(i < s.size()) {
string temp;
temp += s[i];
st.emplace(s[i]);
i ++;
while(!st.empty()) {
if(s[i] == ')') {
st.pop();
} else {
st.emplace('(');
}
temp += s[i];
i ++;
}
if(temp.size() == 2) continue;
res += temp.substr(1, temp.size() - 2);
}
return res;
}
};
简单优化如下:
class Solution {
public:
string removeOuterParentheses(string s) {
stack<char> st;
string res;
int i = 0;
while(i < s.size()) {
st.emplace(s[i]);
i ++;
while(!st.empty()) {
if(s[i] == ')') {
st.pop();
} else {
st.emplace('(');
}
if(!st.empty()) {
res += s[i];
}
i ++;
}
}
return res;
}
};