问题描述
小U得到一个只包含小写字母的字符串 S。她可以执行如下操作:每次选择字符串中两个相同的字符删除,然后在字符串末尾添加一个任意的小写字母。小U想知道,最少需要多少次操作才能使得字符串中的所有字母都不相同?
题目分析 删除两个相同字符,也就是最后要没有相同的字符。只需统计字符串中字符对应的频率数量,然后将其//2累加即可。 本题较为容易。
def solution(S: str) -> int:
# PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
# write code here
fre_dict={}
for char in S:
if char in fre_dict:
fre_dict[char]+=1
else:
fre_dict[char]=1
frq_list =fre_dict.values()
count=0
for l in frq_list:
count+=l//2
return count
if __name__ == '__main__':
print(solution(S = "abab") == 2)
print(solution(S = "aaaa") == 2)
print(solution(S = "abcabc") == 3)