387. 字符串中的第一个唯一字符

利用hashmap的key唯一属性来实现,迭代一遍,

以迭代到的字符为key,计算字符出现的次数。

第二次迭代的时候判断该字符是否只出现了一次。

时间O(n),空间O(m),m为字符串s内元素的离散程度,比如

s的范围是26个小写字母,m就是26

public int firstUniqChar(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }
        for (int i = 0; i < s.length(); ++i) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
争取早日不再是一只菜鸡
原文地址:https://www.cnblogs.com/jchen104/p/14591294.html