我在做反括号

def reverse_parentheses(s):
    """
    Reverse the strings contained in each pair of matching parentheses,
    starting from the innermost pair. The results string should not contain
    any parentheses.

    >>> reverse_parentheses('a(bc)de')
    'acbde'

    >>> reverse_parentheses(
    ...     'The ((quick (brown) (fox) jumps over the lazy) dog)'
    ... )
    'The god quick nworb xof jumps over the lazy'
    """
    chars = list(s)
    open_bracket_indexes = []
    for i, c in enumerate(chars):
        if c == '(':
            open_bracket_indexes.append(i)
        elif c == ')':
            j = open_bracket_indexes.pop()
            chars[j:i] = chars[i:j:-1]
    if open_bracket_indexes:
        raise ArgumentError('Unclosed parenthesis')
    print(''.join(c for c in chars if c not in '()'))
s = input()
reverse_parentheses(s)

description1

描述1要做什么

description2

描述2做什么

result

结果,第10次测试总是失败

我用了很多算法,他们总是在10号失败. 同样的问题也发生在不久前: 堆栈溢出: the source code and a lot of others519/how-do-i-reverse-the-strings-contained-in-each-pair-of-matching-parentheses-sta">seems like the same thing, but nothing works at 10th个 LeetCode: the source code and a lot of others

使用的代码:

cyberforum

leetcode-recursion_based_and_stack_solution, (字面意思是其他leetcode解决方案与之前类似)

这个问题90%的原因是"糟糕"的测试,写得很差,只要这个"问题"存在,下面有链接和答案

推荐答案

以下是使用re的解决方案(我在链接的解决方案中没有看到它).我在leetcode上进行了测试,它通过了所有测试:

import re

s = "The ((quick (brown) (fox) jumps over the lazy) dog)"

while True:
    new_s = re.sub(r"\(([^)(]*)\)", lambda g: g.group(1)[::-1], s)
    if new_s == s:
        break
    s = new_s

print(s)

打印:

The god quick nworb xof jumps over the lazy

enter image description here

Python相关问答推荐

尽管进程输出错误消息,subProcess.check_call的CalledProcess错误.stderr为无

如何处理必须存在于环境中但无法安装的Python项目依赖项?

自定义新元未更新参数

"如果发生特定错误,返回值

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

jit JAX函数中的迭代器

Pystata:从Python并行运行stata实例

带条件计算最小值

沿着数组中的轴计算真实条目

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

有没有一种方法可以从python的pussompy比较结果中提取文本?

如何从pandas的rame类继承并使用filepath实例化

创建可序列化数据模型的最佳方法

如何根据一列的值有条件地 Select 前N组?

Python逻辑操作作为Pandas中的条件

如何在turtle中不使用write()来绘制填充字母(例如OEG)

如何在FastAPI中为我上传的json文件提供索引ID?

将标签移动到matplotlib饼图中楔形块的开始处

如何将数据帧中的timedelta转换为datetime

如何将一组组合框重置回无 Select tkinter?