题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); Map<Character, Integer> map = new HashMap<>(); //将字符串中出现的字母作为map的key,value为这个字母的出现次数 for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (map.containsKey(ch)) { int value = map.get(ch); value++; map.put(ch, value); } else { map.put(ch, 1); } } //这里将map转成List集合,这样就可以通过比较value的大小进行排序 List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, ((o1, o2) -> o1.getValue() - o2.getValue())); //list排完序之后,第一个就是最小值,用minCount来接收 int minCount = list.get(0).getValue(); //这里是要遍历删除出现次数最少的字母 for (Map.Entry<Character, Integer> entry : list) { if (minCount < entry.getValue()) { break; } char ch = entry.getKey(); String delStr = ""; int delIndex = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { delStr = delStr + str.substring(delIndex, i); delIndex = i + 1; } } if (delIndex < str.length() - 1) { delStr = delStr + str.substring(delIndex, str.length()); } str = delStr; } System.out.println(str); } }