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

标签 python algorithm

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

输入: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/

相关文章:

具有 3 列键的 Java Map

java - 这段代码究竟需要做什么?

python - 用 Python 编写的 SQL 查询的语法问题

Python Pandas - 从数据框创建用于乘法的数组或矩阵

python - django 表单不显示或对象不带参数错误

python - 用python中的Pillow替换动态图像中的同一行像素

python - Google App Engine + Django 在项目中有多个应用程序 = ImportError

algorithm - B+树中的批量删除

c++ - 如何在多个文件和类之间传递实例

algorithm - 你将如何对 30gb 文件进行排序,其中重复包含 1 - 1000 个数字