题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
n = input() # 假设用户输入的字符串存储在变量n中 l = {char: n.count(char) for char in n} # 创建字符计数字典 target_string = [char for char in n] # 找出出现次数最小的值 min_count = min(l.values()) # 找出所有出现次数等于最小值的键,同时保持顺序 keys_to_remove = [key for key, value in l.items() if value == min_count] matched_indices = [] for char in keys_to_remove: for i,target_char in enumerate(n): if char == target_char: matched_indices.append(i) print(''.join([target_string[i] for i in range(len(target_string)) if i not in matched_indices]))
构造一个字典用来统计各字符重复次数按依次出现顺序存储,再用一个列表来储存最小出现字符,利用字符串匹配算法,将最小出现字符的列表和目标字符串的列表进行匹配,分为两层进行匹配遍历,并且将匹配的字符索引记录下