题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return int整型 */ public int FirstNotRepeatingChar (String str) { if (str == null || "".equals(str)) { return -1; } char[] chars = str.toCharArray(); Map<Character, Integer> map = new LinkedHashMap<>(); for (char c : chars) { if (map.get(c) == null) { map.put(c, 1); } else { map.put(c, map.get(c) + 1); } } for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() == 1) { return str.indexOf(entry.getKey()); } } return -1; } }