剑指offer——python【第54题】字符流中第一个不重复的字符
2024-09-28 06:04:26
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"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)
最新文章
- MVC Nhibernate 示例
- JavaScript常用技术总结!~~
- PTA Strongly Connected Components
- python 的import机制2
- android常见错误-Unexpected namespace prefix ";xmlns"; found for tag LinearLayout
- Flash Builder4.6破解方案(亲测有效)(转)
- 转载:解决linux ping: unknown host www.baidu.com
- oracle DBLink
- Selenium之偷懒教程
- solr主从复制
- win32下Socket编程(转载)
- 使用Stack堆栈集合大数据运算
- ASP.NET没有魔法——ASP.NET MVC 与数据库之Entity Framework Migrations
- Spring+Spring MVC+MyBatis框架集成
- Ubuntu16.04安装NVIDA驱动和CUDA
- poj 3090 Visible Lattice Points(离线打表)
- js自定义格式化时间戳的格式
- js自动运行
- VIM for C++ 一键安装配置
- HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
热门文章
- ThunderBird对只有回复地址的邮件过滤
- [Python设计模式] 第19章 分公司=部门?——组合模式
- debian linux sudo 无法执行以添加普通用户到sudo
- 【Android自己定义控件】圆圈交替,仿progress效果
- Docker的学习
- Bizatlk Accelerator for RosettaNet安装与配置
- 关于web项目创建后WEB-INF下面没有出现web.xml的解决方法
- Session 在分布式系统中实现方式
- users-and-groups-in-linux
- django项目添加utf-8编码支持中文