题目链接:https://leetcode.com/problems/remove-outermost-parentheses/
难度:easy
解题思路:
本题考查堆栈,在遍历字符串时最好不要删除或者增加字符串元素(i.e.,不要改变长度),不然遍历过程会混乱,因此本题采取标记的方法,将要删除的元素位置先标记起来,然后在遍历读取一遍就行了.
代码:
class Solution {
public:
string removeOuterParentheses(string S) {
stack<int> st;
string ans;
int len=S.size();
vector<bool> v(len,false);
for(int i=0;i<len;i++){
if(S[i]=='(') st.push(i);
else if(S[i]==')'){
int tmp=st.top();
st.pop();
if(st.empty()){
v[tmp]=true;
v[i]=true;
}
}
}
for(int i=0;i<len;i++){
if(v[i]==false) ans.push_back(S[i]);
}
return ans;
}
};