Python – 从字符串中删除 K 长度的重复项
给定一个字符串,删除所有 K 长度的重复项。
Input : test_str = ‘geeksforfreeksfo’, K = 3
Output : geeksforfree
Explanation : eek, eks, ksf, sfo already in string, hence removed.
Input : test_str = ‘geeksforg’, K = 3
Output : geeksforg
Explanation : No repeated string, nothing removed.
方法:使用循环+切片
在此,我们跟踪遇到的所有 K 长度 substrs,使用切片提取,并检查每次重复,如果发生则将其删除。
Python3
# Python3 code to demonstrate working of
# Remove K length Duplicates from String
# Using loop + slicing
# initializing strings
test_str = 'geeksforfreeksfo'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 3
memo = set()
res = []
for idx in range(0, len(test_str) - K):
# slicing K length substrings
sub = test_str[idx : idx + K]
# checking for presence
if sub not in memo:
memo.add(sub)
res.append(sub)
res = ''.join(res[ele] for ele in range(0, len(res), K))
# printing result
print("The modified string : " + str(res))
输出
The original string is : geeksforfreeksfo
The modified string : geeksforfree