题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
def func(): str1 = input() def del_min_count_char(resource_str) -> str: # 如果字符长度只有1,则直接输出 if len(str1) == 1: print(str1) else: # 先定义一个统计每个字符数量的字典,统计每个字符的数量 char_count_dict = {} # 遍历数组,统计每个字符存在的数量 for i in range(len(resource_str)): current_char = resource_str[i] if current_char in char_count_dict: # 如果当前字符已经统计过,则数量加1 char_count_dict[current_char] = char_count_dict[current_char] + 1 else: # 否则数量初始化1 char_count_dict[current_char] = 1 # 因为数量最少的字符可能为1个或多个,所以定义一个list,存放存在数量最少的字符 min_count_char_list = [] # 先定义一个最少字符的数量,初试值设为字符串的长度 min_count = len(resource_str) # 遍历统计字符数量的字典 for key, val in char_count_dict.items(): if val < min_count: # 如果当前的字符数量小于最小字符数量,则清空最小数量字符集合,重新添加当前字符,重新设置最小值 min_count_char_list.clear() min_count_char_list.append(key) min_count = val if val == min_count: # 如果当前的字符数量等于最小字符数量,则追加当前字符 min_count_char_list.append(key) # 遍历最小字符集合,从原始字符中删除最小字符 for char in min_count_char_list: resource_str = str(resource_str).replace(char, '') return resource_str print(del_min_count_char(str1)) if __name__ == '__main__': func()