如何从数组中删除特定元素,同时又不删除其后继出现

时间:2019-04-12 09:40:48

标签: python arrays algorithm list

从用户处获取整数输入,然后从数组中删除具有这些连续出现次数的数组中的元素。

例如,输入数组为“ aabcca”,而用户输入为2。 那么答案应该是“ ba”。

当元素不重复时我尝试过。我的代码非常适合“ aaabbccc”之类的示例。

for j in range(t, (n+1)):
    if (t == n):
        if (count == k):
            array = [x for x in array if x != temp]
        print array
        exit()
    if (t == n and count == k):
        array = [x for x in array if x != temp]
        print array
        exit()
    if temp == data[j]: 
        count += 1
        t += 1
    if temp != data[j]:
        if count == k:
            array = [x for x in array if x != temp]
        temp = data[t]
        count = 1
        t += 1

2 个答案:

答案 0 :(得分:0)

您可以使用sliding windowtwo pointers来解决。

关键点是使用[start, end]范围记录连续的序列,并且仅添加长度小于n的序列:

def delete_consecutive(s, n):
    start, end, count = 0, 0, 0
    res, cur = '', ''
    for end, c in enumerate(s):
        if c == cur:
            count += 1
        else:
            # only add consecutive seq less than n
            if count < n:
                res += s[start:end]
            count = 1
            start = end
            cur = c

    # deal with tail part
    if count < n:
        res += s[start:end+1]

    return res

测试并输出:

print(delete_consecutive('aabcca', 2))      # output: ba
print(delete_consecutive('aaabbccc', 3))    # output: bb

希望对您有所帮助,如果还有其他问题,请发表评论。 :)

答案 1 :(得分:0)

这是一种实现方法:

def remove_consecutive(s, n):
    # Number of repeated consecutive characters
    count = 0
    # Previous character
    prev = None
    # Pieces of string of result
    out = []
    for i, c in enumerate(s):
        # If new character
        if c != prev:
            # Add piece of string without repetition blocks
            out.append(s[i - (count % n):i])
            # Reset count
            count = 0
        # Increase count
        count += 1
        prev = c
    # Add last piece
    out.append(s[len(s) - (count % n):])
    return ''.join(out)

print(remove_consecutive('aabcca', 2))
# ba
print(remove_consecutive('aaabbccc', 2))
# ac
print(remove_consecutive('aaabbccc', 3))
# bb