思路:
1,利用map记录每个字符出现的次数
2,遍历字符数组,找到第一次出现次数为1的字符
3,时间复杂度为O(n)
代码:
private static void getCharIndex(String str) { Map<Character,Integer> charactCountMap = new HashMap<>(); char[] chars = str.toCharArray(); for (char c : chars) { Integer count = charactCountMap.get(c); if(count == null){ count = 0; } count++; charactCountMap.put(c,count); } for (char aChar : chars) { Integer count = charactCountMap.get(aChar); if(count == 1){ System.out.println("char:"+aChar); return; } } }