0
点赞
收藏
分享

微信扫一扫

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

影子喵喵喵 2022-03-11 阅读 81

https://leetcode-cn.com/problems/first-unique-character-in-a-string/
思路

  • 使用 HashMap 维护元素的出现次数, key 是元素, value 是出现次数
  • 遍历数组, 根据当前元素获取 map 的出现次数, 如果为 1 就返回当前索引
 public int firstUniqChar(String s) {
        // 存储字符:出现次数的映射
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char key = s.charAt(i);
            map.put(key, map.getOrDefault(key, 0) + 1);
        }

        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return  - 1;
    }```

举报

相关推荐

0 条评论