
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 bereverseParentheses(s) = "acbde"
.
我的解答:
我也是佩服我能这样写出来.....
def reverseParentheses(s):
li = []
for x in s:
li.append(x)
while '(' in li:
for i in li:
if i == ')':
for j in range(li.index(i)-1,0,-1):
if li[j] == '(':
y = li.index(i)
z = j
li.pop(li.index(i))
li.pop(j)
l = []
l3 = []
for p in range(z, y-1):
l.append(p)
l2 = sorted(l, reverse=True)
for m in l:
l3.append(li[l2[l.index(m)]])
li[z:y-1] = l3
break
continue
s = ''.join(li)
return s
else:
s = ''.join(li)
return s
膜拜大佬:
def reverseParentheses(s):
for i in range(len(s)):
if s[i] == "(":
start = i
if s[i] == ")":
end = i
return reverseParentheses(s[:start] + s[start+1:end][::-1] + s[end+1:])
return s