题解 | 第一个只出现一次的字符
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
import java.util.*; public class Solution { // 找到第一个只出现一次的字符,并返回它的位置 // 重点:只出现一次,第一个,所以需要整个遍历字符串 // 还需要有序 public int FirstNotRepeatingChar (String str) { // write code here // 第一个map记录索引 HashMap<Character,Integer> map = new HashMap<>(); // 第二个map记录次数 HashMap<Character,Integer> map_count = new HashMap<>(); int len = str.length(); for(int i = 0; i < len; i++){ char c = str.charAt(i); if(map.containsKey(c)){ map_count.put(c,map_count.get(c) + 1); }else{ map.put(c,i); map_count.put(c,1); } } for(int i = 0;i<len;i++){ if(map_count.get(str.charAt(i)) == 1){ return map.get(str.charAt(i)); } } return -1; } }