leetcode周赛上的第二题,难度中等。
题目
给出一个字符串 s
(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
示例 1:
输入:s = "(abcd)" 输出:"dcba"
示例 2:
输入:s = "(u(love)i)" 输出:"iloveu"
示例 3:
输入:s = "(ed(et(oc))el)" 输出:"leetcode"
示例 4:
输入:s = "a(bcdefghijkl(mno)p)q" 输出:"apmnolkjihgfedcbq"
提示:
0 <= s.length <= 2000
s
中只有小写英文字母和括号- 我们确保所有括号都是成对出现的
通过的C++代码:(主要参考了讨论区https://leetcode-cn.com/circle/discuss/0znlIe/view/NEOxvF/)
class Solution {
public:
string reverseParentheses(string s) {
//注意理解题意,从最内层的括号开始遍历
//用栈实现字符串翻转的过程
stack<char> totalstack;
string temp;
for(int i=0;i<s.length();i++){
if(s[i]==')'){
temp="";
while(totalstack.top()!='('){
temp+=totalstack.top();
totalstack.pop();
}
totalstack.pop();//pop掉左括号
for(int m=0;m<temp.length();m++){
totalstack.push(temp[m]);
}
}
else{
totalstack.push(s[i]);
}
}
string res;
while(!totalstack.empty()){
//stack不能随机访问,只能pop出来res+=totalstack[i];
res=res.insert(0,1,totalstack.top());
//insert是有返回值的,不定义会报错missing template arguments before '.' token
totalstack.pop();
}
return res;
}
};