从用户处获取整数输入,然后从数组中删除具有多个连续出现次数的数组中的元素。
例如,输入数组为“ 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
您可以使用sliding window
或two 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
希望对您有所帮助,如有其他问题,请发表评论。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句