本题主要采用贪心算法、字典来完成。
字典保存的是每组数据中第i的元素出现的次数。
def solve(s, k):
n = len(s)
if n//k != n/k:
return -1
Size= n//k
nums = [dict() for _ in range(Size)]
for i in range(0,n,Size):
for j in range(Size):
nums[j][s[i+j]] = nums[j].get(s[i+j], 0) + 1
model = [0 for _ in range(Size)]
for i in range(Size):
model[i] = max(nums[i].values())
ans = 0
for i in range(Size):
ans += k-model[i]
print(ans)
return 1
# 贪心算法
k = int(input())
s = input()
if solve(s, k) == -1:
print("-1")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)