1190. Reverse Substrings Between Each Pair of Parentheses
- Reverse Substrings Between Each Pair of Parentheses python solution
题目描述
You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.

解析
直接法求解,出现几次()就翻转几次
// An highlighted block
class Solution:
def reverseParentheses(self, s: str) -> str:
stack = ['']
for c in s:
if c == '(':
stack.append('')
elif c == ')':
add = stack.pop()[::-1]
stack[-1] += add
else:
stack[-1] += c
return stack.pop()
上两张图帮助理解算法的过程




Reference
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/383670/JavaC%2B%2BPython-Why-not-O(N)
探讨了一种解决LeetCode题目的方法:逆置每对匹配括号内的字符串,从最内层开始,最终结果不含括号。通过Python实现,使用栈结构存储字符串片段,遇到左括号入栈,右括号则取出并逆置栈顶元素。
420

被折叠的 条评论
为什么被折叠?



