首页 > 解决方案 > 去掉括号

问题描述

最近我在解决 Codewars 中的一个问题并卡住了。问题链接的链接

基本上它要求的是:

例如,您将获得一个字符串:

"example(unwanted thing)example"

您的任务是删除括号内的所有内容以及括号本身。

上面的示例将返回:

"exampleexample"
  1. 不要担心其他括号,例如“[]”和“{}”,因为它们永远不会出现。
  2. 可以有多个括号。
  3. 括号可以嵌套。

下面给出了一些其他的测试用例:

test.assert_equals(remove_parentheses("hello example (words(more words) here) something"), "hello example  something")
test.assert_equals(remove_parentheses("(first group) (second group) (third group)"), "  ")

我在网上查了一下,找到了一些涉及 Regex 的解决方案,但我想在没有 Regex 的情况下解决这个问题。

到目前为止,我已经尝试过类似的解决方案,如下所示:

def remove_parentheses(s):
    
    while s.find('(') != -1 or s.find(')') != -1 :
        f = s.find('(')
        l = s.find(')')
        s = s[:f] + s [l+1:]
    return s

但是当我尝试运行这个片段时,我得到了Execution Timed Out

标签: pythonstringalgorithm

解决方案


您只需要跟踪开括号的数量(嵌套深度,技术上),以查看当前字符是否应包含在输出中。

def remove_parentheses(s):
    parentheses_count = 0
    output = ""
    for i in s:
        if i=="(":
            parentheses_count += 1 
        elif i==")":
            parentheses_count -= 1 
        else:
            if parentheses_count == 0:
                output += i 
    return output

print(remove_parentheses("hello example (words(more words) here) something"))
print(remove_parentheses("(first group) (second group) (third group)"))

推荐阅读