题目:删除字符串中出现次数最少的字符,如果有多个字符出现次数同为数量最少,则一起删除,最后返回
示例:
1、“abccdede” 返回:“ccdede”
2、“abcabc” 返回:null
3、“” 返回:null
import java.util.*; public class DeleteStringsMinChar { public static void main(String[] args) { String str = "abccdede"; String str2 = "abcabc"; String str3 = ""; System.out.println(getResult(str)); System.out.println(getResult(str2)); System.out.println(getResult(str3)); } public static String getResult(String str){ if (str.length() == 0) return null; char[] chars = str.toCharArray(); //存储字符串中字符对应的数量 HashMap<Character, Integer> charHashMap = new HashMap<Character, Integer>(); for (char aChar : chars) { if (charHashMap.containsKey(aChar)){ charHashMap.put(aChar, charHashMap.get(aChar) + 1); } else { charHashMap.put(aChar, 1); } } //存储需要删除的元素 HashSet<Character> characters = new HashSet<>(); //存储字符最少的数量 Integer minLen = Integer.MAX_VALUE; Set<Map.Entry<Character, Integer>> entries = charHashMap.entrySet(); //获取字符串中最小元素数量 for (Map.Entry<Character, Integer> e : entries) { Integer val = e.getValue(); Character key = e.getKey(); if (minLen > val) { characters.clear(); minLen = val; characters.add(key); }else if (minLen == val){ characters.add(key); } } //剥去需要删除的字符的返回所需字符串 StringBuffer stringBuffer = new StringBuffer(); for (char aChar : chars) { if (!characters.contains(aChar)){ stringBuffer.append(aChar); } } return stringBuffer.length() == 0 ? null : stringBuffer.toString(); } }
結果:
ccdede null null