题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return int整型 */ public int FirstNotRepeatingChar (String str) { // write code here if (str == null || str.length() == 0) { return -1; } // 将字符串转化为字符数组 char[] arr = str.toCharArray(); int res = -1; // 记录字符出现的次数 HashMap<Integer, Integer> hashMap = new HashMap<>(); for(int i = 0; i < arr.length; i ++) { if (hashMap.containsKey((int)arr[i])) { Integer value = hashMap.get((int) arr[i]); hashMap.put((int)arr[i], value + 1); } else { hashMap.put((int)arr[i], 1); } } // 找到第一个只出现一次的字符 for(int i = 0; i < arr.length; i ++) { if (hashMap.get((int) arr[i]) > 1){ continue; } else { res = i; break; } } return res; } }