TreeviewCopyright © aleen42 all right reserved, powered by aleen42

50. 第一个只出现一次的字符

https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/

Java

class Solution {

    // 哈希表
    public char firstUniqChar(String s) {
        // 初始化hashMap
        HashMap<Character, Boolean> dic = new HashMap<>();
        // 将字符串转换为字符数组
        char[] chars = s.toCharArray();
        // 遍历字符数组,并将字符逐个存储到hashMap集合中
        // 其键用于存储字符,而值为布尔值,其用于存储字符出现的次数是否为1
        for(char c : chars) 
            dic.put(c, !dic.containsKey(c));
        // 再次遍历字符数组,取出第一个只出现一次的字符
        for(char c : chars) 
            if(dic.get(c)) return c;
        // 若无果则返回空格
        return ' ';
    }
}

Python

class Solution(object):

    # 哈希表
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: str
        """
        dic = {}
        # Python 代码中的 not c in dic 整体为一个布尔值
        # c in dic 为判断字典中是否含有键 c 
        for c in s:
            dic[c] = not c in dic
        for c in s:
            if dic[c]: return c
        return ' '
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""