【问题标题】:Find max length between parenthesis查找括号之间的最大长度
【发布时间】:2018-09-16 06:22:03
【问题描述】:

如何在混合括号(包括左括号和右括号)的字符串中找到()[] 之间的最大距离差。

例如:

s = '()[(([]))]([[]])'

len_diff(s, '()') # -> 6 As s = 
                              # ()   [(([]))]   ([[]])
                              #       ^    ^    ^    ^

len_diff(s, '[]') # -> 8 As s = 
                              # ()   [(([]))]   ([[]])
                              #      ^      ^

允许使用任何类型的嵌套括号,并且输入始终有效

【问题讨论】:

  • 例子不是很清楚。为什么不计算s开头的()?在查找“()”的长度时,您是否只计算“(”和“)”的数量而不计算方括号?最好再举一些例子(也许对预期的输出做一些解释)
  • 我想找到左括号和右括号之间的最大距离

标签: python string python-3.x substring


【解决方案1】:

解决此问题的一种方法是使用堆栈。当你看到一个左括号时,你把它压入堆栈,当你看到一个右括号时,你弹出堆栈。只要堆栈不为空,您就会一直计算从字符串中读取的字符数。一旦堆栈变空,您可以测试这是否是最大距离并更新您的max_length 变量。或者,这也可以通过评论中提到的递归来完成。

def len_diff(s, paren_type='()'):
    stack = []
    length = 0
    max_length = 0
    # Good to add checks here on length of paren_type
    open_paren = paren_type[0]
    close_paren = paren_type[1]

    for c in s:
        if c == open_paren:
            stack.append(c)
        elif c == close_paren:
            stack.pop()
        if len(stack) == 0:
            if length > max_length:
                max_length = length + 1
            length = 0  # reset the counter for next paren
        else:
            # we only want to start counting after seeing at least
            # one open paren, i.e. when the stack is not empty
            length += 1

    return max_length

【讨论】:

    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2018-07-10
    相关资源
    最近更新 更多