如图
package com.yang;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @BelongsProject: untitled
* @BelongsPackage: com.yang
* @Author: yzh
* @CreateTime: 2023-11-28
*/
/*
题目:删除字符串中出现次数最少的字符,如果有多个字符出现次数同为数量最少,则一起删除,最后返回
示例:
1、“abccdede” 返回:“ccdede”
2、“abcabc” 返回:null
3、“” 返回:null
*/
public class MyTest {
public static void main(String[] args) {
String a = "aabbcc";
//null
System.out.println(getResult(a));
String b ="avvcc";
//vvcc
System.out.println(getResult(b));
}
/**
* 删除字符串中出现次数最少的字符
* @param str
* @return
*/
public static String getResult(String str){
if (str.length() ==0){
return null;
}
char[] chars = str.toCharArray();
//用HashMap集合统计字符出现次数
HashMap<Character, Integer> map = new HashMap<>();
for (char c : chars) {
if (!map.containsKey(c)){
map.put(c,0);
}else {
map.put(c,map.get(c)+1);
}
}
// 找到最少出现次数
Character key = getMinValueKey(map);
Integer min = map.get(key);
// 删除最少出现次数的字符
StringBuilder stringBuilder = new StringBuilder();
for (char c : chars) {
if (map.get(c) > min){
stringBuilder.append(c);
}
}
String s = stringBuilder.toString();
if (s.equals("")){
return null;
}
return s;
}
/**
* 遍历HashMap获取value最小的建
* @param map
* @return
*/
public static Character getMinValueKey(HashMap<Character, Integer> map) {
//创建一个变量来保存当前最小的 value 和对应的键。
Map.Entry<Character,Integer> minEntry = null;
//获取 HashMap 中的键值对(Entry)集合
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
if (minEntry == null || minEntry.getValue() > entry.getValue()){
minEntry = entry;
}
}
return minEntry.getKey();
}
}