题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String string = scanner.next(); char[] chars = string.toCharArray(); LinkedHashSet<String> set = new LinkedHashSet<>(); ArrayList<String> strList = new ArrayList<>(); for (int i = 0; i < chars.length; i++) { strList.add(chars[i] + "");// 转换成list,为最后删除做准备 set.add(chars[i] + "");// 去重 } ArrayList<Integer> list = new ArrayList<>();// 存放每个元素的个数 ArrayList<String> listStr = new ArrayList<>();// 存放去重后的元素 for (String chStr : set) { int count = 0; for (int i = 0; i < chars.length; i++) { if (chStr.equals(chars[i] + "")) { count++; } } list.add(count); listStr.add(chStr); } Integer min = Collections.min(list);// 找到出现次数最少的次数,再找到他的下标 ArrayList<Integer> listIndex = new ArrayList<>();// 存放次数最少的下标 for (int i = 0; i < list.size(); i++) { if (min.equals(list.get(i))) { listIndex.add(i); } } ArrayList<String> strings = new ArrayList<>();// 存放出现次数最少的元素 for (int i = 0; i < listIndex.size(); i++) { String s = listStr.get(listIndex.get(i)); strings.add(s); } for (int i = 0; i < strings.size(); i++) { for (int j = 0; j < strList.size(); j++) { if (strings.get(i).equals(strList.get(j))) { String removeStr = strList.remove(j);// 删除出现次数最少的元素 } } } // 得到的strList就是结果,转换成字符串输出。 for (String s : strList) { System.out.print(s); } } }