Code Signal_练习题_reverseParentheses

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

猜你喜欢

转载自www.cnblogs.com/YD2018/p/9357496.html
今日推荐