python - 去掉括号
问题描述
最近我在解决 Codewars 中的一个问题并卡住了。问题链接的链接
基本上它要求的是:
例如,您将获得一个字符串:
"example(unwanted thing)example"
您的任务是删除括号内的所有内容以及括号本身。
上面的示例将返回:
"exampleexample"
- 不要担心其他括号,例如“[]”和“{}”,因为它们永远不会出现。
- 可以有多个括号。
- 括号可以嵌套。
下面给出了一些其他的测试用例:
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。
解决方案
您只需要跟踪开括号的数量(嵌套深度,技术上),以查看当前字符是否应包含在输出中。
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)"))
推荐阅读
- arrays - 按下特定按钮时,应用程序崩溃
- javascript - 在名称空间内定义映射
- javascript - 从 JSON 对象中添加和删除的函数
- jenkins - 如果我的构建阶段在詹金斯管道中失败,如何跳过该阶段?
- javascript - 如何防止浏览器调用 Digest auth 弹出窗口并使用 Jquery 处理 401 错误?
- c++ - “无效比较器”:重载“<”运算符时出错
- javascript - Javascript:创建具有多个循环的对象
- excel - 如何在单个单元格中找到最高值和最低值
- java - 如何解析未声明为双倍的 XML 函数日期?
- java - Java反射,从不同的包创建私有类的对象