给出一个字符串 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++
class Solution { public: string reverseParentheses(string s) { string res; int n=s.length(); vector<string> vec; for(int i=0;i<n;i++) { if('('==s[i]) { vec.push_back(""); } else if(')'==s[i]) { string str=vec.back(); vec.pop_back(); reverse(str.begin(),str.end()); if(vec.size()) { vec.back()+=str; } else { res+=str; } } else { if(vec.size()) { vec.back()+=s[i]; } else { res+=s[i]; } } } return res; } };
python
class Solution: def reverseParentheses(self, s: str) -> str: res="" n=len(s) tmp=[] for i in range(n): if '('==s[i]: tmp.append("") elif ')'==s[i]: ss=tmp[-1] ss=ss[::-1] del tmp[-1] if len(tmp): tmp[-1]+=ss else: res+=ss else: if len(tmp): tmp[-1]+=s[i] else: res+=s[i] return res
来源:51CTO
作者:我很忙2010
链接:https://blog.csdn.net/qq_27060423/article/details/100855890