Code Signal_练习题_reverseParentheses

本文介绍了一种算法,用于反转字符串中由匹配括号包围的子串,从最内层括号开始处理,最终得到不含括号的结果字符串。通过递归方法实现,示例代码清晰展示了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You have a string s that consists of English letters, punctuation marks, whitespace characters, and brackets. It is guaranteed that the parentheses in s form a regular bracket sequence.

Your task is to reverse the strings contained in each pair of matching parentheses, starting from the innermost pair. The results string should not contain any parentheses.

Example

For string s = "a(bc)de", the output should be
reverseParentheses(s) = "acbde".

 

 

我的解答:

 1 我也是佩服我能这样写出来.....
 2 def reverseParentheses(s):
 3     li = []
 4     for x in s:
 5         li.append(x)
 6     while '(' in li:
 7         for i in li:
 8             if i == ')':
 9                 for j in range(li.index(i)-1,0,-1):
10                     if li[j] == '(':
11                         y = li.index(i)
12                         z = j
13                         li.pop(li.index(i))
14                         li.pop(j)
15                         l = []
16                         l3 = []
17                         for p in range(z, y-1):
18                             l.append(p)
19                         l2 = sorted(l, reverse=True)
20                         for m in l:
21                             l3.append(li[l2[l.index(m)]])
22                         li[z:y-1] = l3
23                         break
24         continue
25         s = ''.join(li)
26         return s
27     else:
28         s = ''.join(li)
29         return s

 

膜拜大佬:

1 def reverseParentheses(s):
2     for i in range(len(s)):
3         if s[i] == "(":
4             start = i
5         if s[i] == ")":
6             end = i
7             return reverseParentheses(s[:start] + s[start+1:end][::-1] + s[end+1:])
8     return s
View Code

 

转载于:https://www.cnblogs.com/BlameKidd/p/9357496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值