博客
关于我
剑指offer系列-面试题50. 第一个只出现一次的字符 (python)
阅读量:533 次
发布时间:2019-03-08

本文共 601 字,大约阅读时间需要 2 分钟。

  • 题目

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

  • 解题思路

    使用哈希表保存字符是否只出现一次。在Python中,字典(dict)在3.6及以上版本中是有序的,所以直接遍历字典找到第一个符合条件的字符即可。

  • 代码实现

    使用哈希表记录字符出现次数。如果使用数字来记录,需要遍历字符然后更新计数,再在字典中查找计数为1的字符。为了节省空间,可以使用布尔值来代替数字,这样可以减少内存占用并使代码更简洁。

  • class Solution:    def firstUniqChar(self, s: str) -> str:        record = {}        for char in s:            record[char] = char not in record  # 否定逻辑将布尔代替了数字        for k in record:            if record[k]:                return k        return " "
    1. 代码优化

      使用布尔值代替数字,可以更加节省空间。这种方法不仅提高了代码的效率,还减少了内存的占用。

    2. 总结

      在算法中,熟练使用哈希表能够有效地帮助实现算法。如果能够熟练掌握哈希表的应用,那么在解决类似的问题时就能够更加高效。

    3. 参考文献

      (无具体文献需求)

    转载地址:http://ijsiz.baihongyu.com/

    你可能感兴趣的文章
    NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>