1、描述
给出一个字符串 s(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
示例 1:
输入:s = “(abcd)”
输出:“dcba”
示例 2:
输入:s = “(u(love)i)”
输出:“iloveu”
来源:力扣(LeetCode)
[链接][https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字
字符,去除小括号,逆置
3、思路
使用栈,和队列,使用栈一次遍历把字符串进栈,然后边进栈边处理,遇到一个右括号,就进行逆置处理,(通过队列进行处理)
4、notes
5、复杂度
时间:O(N)
空间O(N)
6、code
class Solution {
public:
string reverseParentheses(string s) {
string res;
stack<char>st;
queue<char>que;
for (auto tem :s){
if (tem != ')'){ // 不是右括号 就 入栈
st.push(tem);
}
else {
char tem2 = st.top(); // 当是右括号时,就把栈中从上到下到左括号的字符搞到队列中,
while (tem2 != '('){
que.push(tem2);
st.pop();
tem2 = st.top();
}
st.pop();
}
while (!que.empty()){ // 消减一对小括号之后,再次入栈
st.push(que.front());
que.pop();
}
}
while (!st.empty()){ // 出栈之后,就是结果集的逆序,
res +=(st.top());
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};