我正在使用python进行编码挑战,规则是取一个字符串,并且相同字符但大小写不同的任何两个相邻字母都应删除。重复此过程,直到没有并排的不同大小写的匹配字母为止。最后,应该打印字符串的长度。我在下面做了一个从左到右迭代的解决方案。尽管有人告诉我,有更好的更有效的方法。
list_of_elves=list(line)
n2=len(list_of_elves)
i=0
while i < len(list_of_elves):
if list_of_elves[i-1].lower()==list_of_elves[i].lower() and list_of_elves[i-1] != list_of_elves[i]:
del list_of_elves[i]
del list_of_elves[i-1]
if i<2:
i-=1
else:
i-=2
if len(list_of_elves)<2:
break
else:
i+=1
if len(list_of_elves)<2:
break
print(len(list_of_elves))
我也做了一些伪代码
Two adjacent matching letters
&& Of differing case
例如,如果我们有一个带有'aAa'的字符串,那么'aA'将被删除,而后跟'a'。
这与匹配括号非常相似,但是匹配不是大写对,而是大写/小写。您可以使用类似的技术来维护堆栈。然后遍历并将当前字母与堆栈顶部进行比较。如果匹配,则将元素弹出堆栈;如果他们不将字母附加到堆栈上。最后,堆栈的长度将是您的答案:
line = "cABbaC"
stack = []
match = lambda m, n: m != n and m.upper() == n.upper()
for c in line:
if len(stack) == 0 or not match(c, stack[-1]):
stack.append(c)
else:
stack.pop()
stack
# stack is empty because `Bb` `Aa` and `Cc` get deleted.
类似地,line = "cGBbgaCF"
将导致['c', 'a', 'C', 'F']
的堆栈,因为Bb
,然后Gg
被删除。