zoukankan      html  css  js  c++  java
  • 剑指offer——python【第54题】字符流中第一个不重复的字符

    题目描述

    请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。如果当前字符流没有存在出现一次的字符,返回#字符。

    思路

    和前面的那道字符串中只出现一次的字符相似而不相同,前面那道是固定长度字符串,而本题是字符流,也就是会增长的,每次字符串多一个字符,就要重新判断是哪个只出现一次的字符

    因为牛客网里剑指offer的python只有2.7,没有3.0以上的版本,而python2.7的字典遍历通常不是有序的(python3通常有序),所以只能再借助一个列表来存储全部字符串,遍历字符串从而寻找

    解答

    class Solution:
        # 返回对应char
        def __init__(self):
            self.charDict = {}#存放字符和对应的数量
            self.charlist = []#存放字符
        def FirstAppearingOnce(self):
            # write code here
            for key in self.charlist:
                if self.charDict[key]==1:
                    return key
            return '#'
        def Insert(self, char):
            # write code here
            self.charDict[char]=1 if char not in self.charDict else self.charDict[char]+1
            self.charlist.append(char)

    其实再想一下,把字典去掉也完全可以啊,这跟那道固定长度的只出现一次字符串没有本质的区别

    class Solution:
        # 返回对应char
        def __init__(self):
            self.charlist = []
        def FirstAppearingOnce(self):
            # write code here
            for key in self.charlist:
                if self.charlist.count(key)==1:
                    return key
            return '#'
        def Insert(self, char):
            # write code here
            self.charlist.append(char)
    人生苦短,何不用python
  • 相关阅读:
    Linux PHP连接MSSQL
    Curl参数一览
    [android开发必备] Android开发者社区汇总
    android定时器
    一个mysql小技巧
    php empty问题
    周报_2012第16周(2012/04/152012/04/21)
    周报_2012第17周(2012/04/222012/04/28)
    周报_2013第04周(2013/01/202013/01/26)
    周报_2013第01周(2012/12/302012/01/05)
  • 原文地址:https://www.cnblogs.com/yqpy/p/9569448.html
Copyright © 2011-2022 走看看