我正在编写一个程序来反转python括号中的子字符串。结果字符串不应包含任何括号。我正在打印b1,b2和ch以进行测试。似乎在while循环内for循环的第二次迭代中,未使用正确的索引更新b1变量。 我试图编写如下解决方案:
def reverseParentheses(s):
r = s
sstring = ''
astring = ''
b1 = b2 = 0
count = 0
for ch in s:
if ch == '(':
count+=1
elif ch ==')':
count+=1
else:
pass
while True:
b1 = b2 = 0
for ch in r:
if ch == '(':
b1 = r.index(ch)
print("b1= ",b1, ch)
if ch == ')':
b2 = r.index(ch)
print("b2= ",b2, ch)
sstring = r[b2-1:b1:-1]
print(r)
print(sstring)
astring = r[0:b1]+sstring+r[b2+1:]
print(astring)
r = astring
break
if len(astring)+count == len(s):
break
return r
s = "a(bcdefghijkl(mno)p)q"
print(reverseParentheses(s))
这是我得到的输出: on 这是我期望的输出: apmnolkjihgfedcbq
答案 0 :(得分:4)
处理嵌套定界符的一种好方法是使用堆栈。当遇到分隔符时,将新集合推入堆栈。 pop()
,当您找到结案时。这样可以保持正确的嵌套顺序。
这是执行此操作的一种方法(它不检查括号是否平衡,但是添加起来并不难):
s = "a(bcdefghijkl(mno)p)q"
stack = [[]] # accumulate letters in stack[0]
for l in s:
if l == '(':
stack.append([]) # start a new level
elif l == ')':
sub = stack.pop()[::-1] # pop the last level and reverse
stack[-1].extend(sub) # add to current
else:
stack[-1].append(l) # add to current
''.join(stack[0]) #'apmnolkjihgfedcbq'
答案 1 :(得分:1)
一种找到括号位置并从里到外反转的方法(这样,包含在偶数个括号之间的那些保持不变),最后摆脱了括号:
s = "a(bcdefghijkl(mno)p)q"
leftp = reversed([pos for pos, char in enumerate(s) if char == "("])
rightp = [pos for pos, char in enumerate(s) if char == ")"]
for i in zip(leftp,rightp):
subs = s[i[0]+1:i[1]][::-1]
s = s[:i[0]+1]+subs+s[i[1]:]
for c in ["(", ")"]:
s = s.replace(c, "")
print(s) # Outputs "apmnolkjihgfedcbq"
编辑
对于。@ Mark Meyer指出的未嵌套的括号,您可以按照here的说明找到它们,并应用相同的规则
def find_parens(s):
toret = {}
pstack = []
for i, c in enumerate(s):
if c == '(':
pstack.append(i)
elif c == ')':
if len(pstack) == 0:
raise IndexError("No matching closing parens at: " + str(i))
toret[pstack.pop()] = i
if len(pstack) > 0:
raise IndexError("No matching opening parens at: " + str(pstack.pop()))
return toret
s = "a(bcd)efghijkl(mno)pq"
parens = find_parens(s)
for leftp, rightp in parens.items():
subs = s[leftp+1:rightp][::-1]
s = s[:leftp+1]+subs+s[rightp:]
for c in ["(", ")"]:
s = s.replace(c, "")
print(s) # Outputs "adcbefghijklonmpq"