问题描述
小U得到一个只包含小写字母的字符串 S
。她可以执行如下操作:每次选择字符串中两个相同的字符删除,然后在字符串末尾添加一个任意的小写字母。小U想知道,最少需要多少次操作才能使得字符串中的所有字母都不相同?
代码
def solution(S: str) -> int:
# PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
# write code here
from collections import Counter
c = list(Counter(S).values())
ans = 0
M = 26
for i in range(len(c)):
if len(c) == M:
break
while c[i] > 2 and len(c) < M:
c.append(1)
c[i] -= 2
ans += 1
for x in c:
ans += x - 1
return ans
if __name__ == '__main__':
print(solution(S = "abab") == 2)
print(solution(S = "aaaa") == 2)
print(solution(S = "abcabc") == 3)