gpt4 book ai didi

python - 从给定字符串中删除偶数个连续重复字符

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:32:33 26 4
gpt4 key购买 nike

我正在尝试解决将字符串作为输入然后删除偶数个重复字符的问题。

输入:azxxzyyyddddyzzz

输出:zzz

你能帮我做这件事吗?

我的尝试在删除重复字符方面工作正常,但我一直坚持如何删除偶数的重复字符

# 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com