public int firstUniqChar(String s) {Map<Character, Integer> map = new HashMap();char[] chars = s.toCharArray();//先统计每个字符的数量for (char ch : chars) {map.put(ch, map.getOrDefault(ch, 0) + 1);}//然后在遍历字符串s中的字符,如果出现次数是1就直接返回for (int i = 0; i < s.length(); i++) {if (map.get(chars[i]) == 1) {return i;}}return -1;}作者:数据结构和算法
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/?discussion=6TyKA7
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。