【leetcode】1190. Reverse Substrings Between Each Pair of Parentheses

题目如下:

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 bracket.

 

 

Example 1:

Input: s = "(abcd)"
Output: "dcba"

Example 2:

Input: s = "(u(love)i)"
Output: "iloveu"

Example 3:

Input: s = "(ed(et(oc))el)"
Output: "leetcode"

Example 4:

Input: s = "a(bcdefghijkl(mno)p)q"
Output: "apmnolkjihgfedcbq"

 

Constraints:

  • 0 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It's guaranteed that all parentheses are balanced.

解题思路:本题和leetcode之前出现过的四则运算的题目类似。从头开始遍历s,不是'('的字符直接入栈,如果遇到')',找出栈中最靠近栈顶的'(',逆置从'('到栈顶的所有元素,同时删除'(',直到s遍历完成为止。

代码如下:

class Solution(object):
    def reverseParentheses(self, s):
        """
        :type s: str
        :rtype: str
        """
        left_inx = []
        stack = []
        for i in s:
            if i == '(':
                stack.append(i)
                left_inx.append(len(stack)-1)
            elif i == ')':
                inx = left_inx.pop(-1)
                sub = stack[inx + 1:]
                sub.reverse()
                stack = stack[:inx] + sub
            else:
                stack.append(i)
        return ''.join(stack)

 

转载于:https://www.cnblogs.com/seyjs/p/11532014.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值