python - 先找到不重复的字符
问题描述
问题:
给定一个由小英文字母组成的字符串 s,找到并返回其中不重复字符的第一个实例。如果没有这样的字符,返回'_'。
例子
对于s = "abacabad"
,输出应该是
firstNotRepeatingCharacter(s) = 'c'
。
这是我到目前为止所拥有的,但它太慢了。如何使运行时间更快?谢谢。
def firstNotRepeatingCharacter(s):
char = set(s)
for i in range(len(s)):
if s.count(s[i]) == 1:
return s[i]
return "_"
解决方案
您可以使用collections.Counter以线性时间计算字符,然后与next一起过滤结果,如下所示:
from collections import Counter
def firstNotRepeatingCharacter(s):
counts = Counter(s)
return next((ch for ch in s if counts[ch] < 2), "_")
print(firstNotRepeatingCharacter("abacabad"))
输出
c
或者简单地使用字典(不需要导入):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return next((ch for ch in s if counts[ch] < 2), "_")
两种方法在输入字符串的长度上都是线性的,您当前的方法是唯一字符的数量O(k*s)
在哪里。k
推荐阅读
- android - 从 JetPack Proto DataStore 读取值
- wordpress - Wordpress 网站在图片之前上传文本
- php - 在 Woocommerce 产品页面上自定义附加按钮
- javascript - 在 JS 中导航 xml 文档的最快方法是什么?
- c - 如何正确进行 GMP 位移?
- r - R,tbl_summary,正确对待连续变量
- sql - 将周聚合分解为日期
- api - 您可以在 google 附近的消息 API 上更新消息吗?
- python - 什么是(for 循环内的 list.index())复杂度
- javascript - 道具类型失败:“object”类型的道具“defaultValue”无效