1 class Solution:
 2     def reverseParentheses(self, s: str) -> str:
 3         stack = ['']
 4         for c in s:
 5             if c == '(':
 6                 stack.append('')
 7             elif c == ')':
 8                 add = stack.pop()[::-1]
 9                 stack[-1] += add
10             else:
11                 stack[-1] += c
12         return stack.pop()

参考:https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/382775/Python3-straightforward-and-easiest-on-discussion

算法思路:栈。

栈中存储字符串,

每遇到一个'(',则新增一个元素——空字符串。

每遇到一个')',则将末位元素出栈->翻转->拼接回前一元素。

每遇到一个字母,则追加到末位元素。

最终栈内只剩下唯一的一个元素,将此元素出栈返回,即为所求。

posted on 2019-09-15 22:45  Sempron2800+  阅读(295)  评论(0编辑  收藏  举报