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;
    }

 

posted @ 2021-03-29 10:18  jchen104  阅读(38)  评论(0编辑  收藏  举报