题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
import java.util.*; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); HashMap<Character, Integer> hashMap = new HashMap<>(); for (int i = 0; i < str.length(); i++) { hashMap.put(str.charAt(i), hashMap.getOrDefault(str.charAt(i), 0) + 1); } LinkedList<Map.Entry<Character, Integer>> entrySet = new LinkedList<>(hashMap.entrySet()); entrySet.sort(new Comparator<Map.Entry<Character, Integer>>() { @Override public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); boolean ifOnce = true; for (int i = 0; i < str.length(); i++) { if (hashMap.get(str.charAt(i)) == 1) { System.out.println(str.charAt(i)); ifOnce = false; break; } } if (ifOnce) System.out.println(-1); } }