题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
利用LinkedHashMap有序的特性,其中key为字符,value为出现的次数,遍历字符串,如果map中不包含当前的字符,则设置value为1,否者在原来的value上加1
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String next = scanner.next(); String result = "-1"; LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(); for (int i = 0; i < next.length(); i++) { String character = String.valueOf(next.charAt(i)); if (linkedHashMap.containsKey(character)) { linkedHashMap.put(character, linkedHashMap.get(character) + 1); } else { linkedHashMap.put(character, 1); } } for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) { if (entry.getValue() == 1) { result = entry.getKey(); break; } } System.out.println(result); } }