美文网首页
offer50第一个只出现一次的字符

offer50第一个只出现一次的字符

作者: D_w | 来源:发表于2022-03-18 15:32 被阅读0次

    在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。

    示例 1:
    输入:s = "abaccdeff"
    输出:'b'
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法:
    初始化: 字典 (Python)、HashMap(Java)、map(C++),记为 dic ;
    字符统计: 遍历字符串 s 中的每个字符 c ;
    若 dic 中 不包含 键(key) c :则向 dic 中添加键值对 (c, True) ,代表字符 c 的数量为 1 ;
    若 dic 中 包含 键(key) c :则修改键 c 的键值对为 (c, False) ,代表字符 c 的数量 > 1。
    查找数量为 1的字符: 遍历字符串 s 中的每个字符 c ;
    若 dic中键 c 对应的值为 True :,则返回 c 。
    返回 ' ' ,代表字符串无数量为 1的字符。
    python

    class Solution:
        def firstUniqChar(self, s: str) -> str:
            dic = {}
            for i in s:
                dic = not i in dic
            for i in s:
                if dic[i]:
                    return i
            return ' '
    

    java

    import java.util.HashMap;
    
    public class Offer50 {
        public char firstUniqChar(String s) {
            HashMap<Character,Boolean>dic = new HashMap<>();
            char[] sc = s.toCharArray();
            for (char c:sc)
                dic.put(c, !dic.containsKey(c));
            for (char c : sc)
                if (dic.get(c)) return c;
            return ' ';
        }
    }
    

    相关文章

      网友评论

          本文标题:offer50第一个只出现一次的字符

          本文链接:https://www.haomeiwen.com/subject/uyoidrtx.html