一. 题目
-
题目
-
示例
二. 方法一: 栈
-
解题思路
- 遍历字符串, 将"("的下标存放到栈中
- 如果遍历到")", 则将栈顶元素和当前下标之间的元素进行反转
- 然后再将字符串中的"(“和”)"删除掉即可
-
解题代码
def reverseParentheses(self, s: str) -> str: arr = list(s) stack = [] res = "" for i in range(len(s)): if s[i] == "(": stack.append(i) elif s[i] == ")": arr[stack[-1] + 1: i] = arr[i - 1:stack[-1]: -1] stack.pop() for ele in arr: if ele != "(" and ele != ")": res += ele return res
-
分析
时间复杂度: O(n^2)
空间复杂度: O(n)
三. 方法二: 虫洞法(题解中看见)
-
解题思路
- 遍历字符串, 将左右括号进行匹配
- 然后重新遍历字符串, 当遇到"(“或”)"时, 直接跳转到右括号, 并改变指针的遍历方向
- 原题解
-
解题代码
def reverseParentheses(self, s: str) -> str: stack, arr = [], [-1] * len(s) flag, size, index = 1, 0, 0 res = "" # 遍历字符串, 将左右括号进行匹配 # 数组中存放匹配的下标值 for i in range(len(s)): if s[i] == "(": stack.append(i) elif s[i] == ")": arr[i] = stack[-1] arr[stack[-1]] = i stack.pop() # 当遍历次数达到字符串的长度时, 说明整个字符串都被遍历了 while size < len(s): # 如果遇到"("或")", 则改变指针移动的方向 if s[index] == "(" or s[index] == ")": flag = - flag # 这里如果不加上flag会导致在匹配的括号间反复横跳 index = arr[index] + flag else: # 按照遍历顺序将字母添加到字符串中 res += s[index] index += flag size += 1 return res
-
分析
时间复杂度: O(n)
空间复杂度: O(n)