我正在尝试解决一个问题,即我将字符串作为输入,然后删除偶数的重复字符。
输入:azxxzyyyddddyzzz
输出:azzz
你能帮我解决这个问题吗?
我的尝试在删除重复字符方面工作正常,但我对如何删除偶数的重复字符感到困惑
# Utility function to convert string to list
def toMutable(string):
temp = []
for x in string:
temp.append(x)
return temp
# Utility function to convert string to list
def toString(List):
return ''.join(List)
# Function to remove duplicates in a sorted array
def removeDupsSorted(List):
res_ind = 1
ip_ind = 1
# In place removal of duplicate characters
while ip_ind != len(List):
if List[ip_ind] != List[ip_ind-1]:
List[res_ind] = List[ip_ind]
res_ind += 1
ip_ind+=1
# After above step string is efgkorskkorss.
# Removing extra kkorss after string
string = toString(List[0:res_ind])
return string
# Function removes duplicate characters from the string
# This function work in-place and fills null characters
# in the extra space left
def removeDups(string):
# Convert string to list
List = toMutable(string)
# Sort the character list
List.sort()
# Remove duplicates from sorted
return removeDupsSorted(List)
# Driver program to test the above functions
string = "geeksforgeeks"
print removeDups(string)
最佳答案
这是使用 itertools.groupby
的尝试。我不确定是否可以以更好的时间复杂度来完成。
from itertools import groupby
def rm_even(s):
to_join = []
for _, g in groupby(s):
chars = list(g)
if len(chars) % 2:
to_join.extend(chars)
if to_join == s:
return ''.join(to_join)
return rm_even(to_join)
演示:
>>> rm_even('azxxzyyyddddyzzz')
>>> 'azzz'
>>> rm_even('xAAAAx')
>>> ''
关于python - 从给定字符串中删除偶数个连续重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377824/