到目前为止,我已经做到了。我被困在递归上。我不知道如何前进,加入和逆转等。
def callrecursion(s):
a=s.index('(')
z=len(s) - string[::-1].index(')') -1
newStr=s[a+1:z]
# Something is missing here i cant figure it out
print(newStr)
return newStr
def reverseParentheses(s):
if '(' in s:
return reverseParentheses(callrecursion(s))
print('wabba labba dub dub')
else:
return s
string='a(bcdefghijkl(mno)p)q'
reverseParentheses(string)
Run Code Online (Sandbox Code Playgroud)
预期的输出:“ apmnolkjihgfedcbq”
def reverseParentheses(s):
if '(' in s:
posopen=s.find('(')
s=s[:posopen]+reverseParentheses(s[posopen+1:])
posclose=s.find(')',posopen+1)
s=s[:posopen]+s[posopen:posclose][::-1]+s[posclose+1:]
return s
string='a(bcdefghijkl(mno)p)q'
print(string)
print(reverseParentheses(string))
print('apmnolkjihgfedcbq') # your test
string='a(bc)(ef)g'
print(string)
print(reverseParentheses(string))
Run Code Online (Sandbox Code Playgroud)
这个想法是尽可能长时间地“向内”(其中“向内”甚至不意味着“嵌套”,只要有左括号,它就会持续),因此最里面的对首先被翻转,然后其余的作为递归返回。这样,“并行”括号似乎也可以工作,而“第一个左括号”与“最后一个右括号”的简单配对并不能很好地处理它们。或者至少我是这么认为的。
rfind这里的复杂替代:
def reverseParentheses(s):
while '(' in s:
posopen=s.rfind('(')
posclose=s.find(')',posopen+1)
s=s[:posopen]+s[posopen+1:posclose][::-1]+s[posclose+1:]
return s;
Run Code Online (Sandbox Code Playgroud)
(... TBH:现在我尝试了,递归魔法在()字符串中放置的空括号上消失,而这个有效)
| 归档时间: |
|
| 查看次数: |
842 次 |
| 最近记录: |