题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"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)

最新文章

  1. MVC Nhibernate 示例
  2. JavaScript常用技术总结!~~
  3. PTA Strongly Connected Components
  4. python 的import机制2
  5. android常见错误-Unexpected namespace prefix "xmlns" found for tag LinearLayout
  6. Flash Builder4.6破解方案(亲测有效)(转)
  7. 转载:解决linux ping: unknown host www.baidu.com
  8. oracle DBLink
  9. Selenium之偷懒教程
  10. solr主从复制
  11. win32下Socket编程(转载)
  12. 使用Stack堆栈集合大数据运算
  13. ASP.NET没有魔法——ASP.NET MVC 与数据库之Entity Framework Migrations
  14. Spring+Spring MVC+MyBatis框架集成
  15. Ubuntu16.04安装NVIDA驱动和CUDA
  16. poj 3090 Visible Lattice Points(离线打表)
  17. js自定义格式化时间戳的格式
  18. js自动运行
  19. VIM for C++ 一键安装配置
  20. HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor

热门文章

  1. ThunderBird对只有回复地址的邮件过滤
  2. [Python设计模式] 第19章 分公司=部门?——组合模式
  3. debian linux sudo 无法执行以添加普通用户到sudo
  4. 【Android自己定义控件】圆圈交替,仿progress效果
  5. Docker的学习
  6. Bizatlk Accelerator for RosettaNet安装与配置
  7. 关于web项目创建后WEB-INF下面没有出现web.xml的解决方法
  8. Session 在分布式系统中实现方式
  9. users-and-groups-in-linux
  10. django项目添加utf-8编码支持中文