LeetCode—剑指Offer:第一个只出现一次的字符(HashMap)

第一个只出现一次的字符(简单)

2020年9月8日

题目来源:力扣

在这里插入图片描述

解题
map中使用布尔值做键值对相对整型更好

class Solution {
    
    
    public char firstUniqChar(String s) {
    
    
        Map<Character,Boolean> map=new HashMap<>();
        char[] ch=s.toCharArray();
        //如果map中出现了,更新为false;没出现过,添加为true
        for(char c:ch){
    
    
            map.put(c,!map.containsKey(c));
        }
        //按顺序取,第一个为true就是结果
        for(char c:ch){
    
    
            if(map.get(c)) return c;
        }
        return ' ';
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108462023