python-3.x - 检查一个集合是否包含在另一个集合中的时间复杂度
问题描述
我正在尝试实现查找s
包含模式的给定字符串的最短子字符串的示例char
。我的代码运行良好,但我的目标是达到O(N)
N 为s
. 这是我的代码;
def shortest_subtstring(s,char):
#smallest substring containing char.use sliding window
start=0
d=defaultdict(int)
minimum=9999
for i in range(len(s)):
d[s[i]]+=1
#check whether all the characters from char has been visited.
while set(char).issubset(set([j for j in d if d[j]>0])):
#if yes, can we make it shorter
length=i-start+1
minimum=min(length,minimum)
if length==minimum:
s1=s[start:i+1]
d[s[start]]-=1
start+=1
return (minimum,s1)
我的问题是在线;
while set(char).issubset(set([j for j in d if d[j]>0]))
每次我检查所有字符串是否char
都保存在我的字典中时,使用is.subset
. 我可以知道如何在我的代码中找到这一步的时间复杂度吗?Is it O(1)
,这对于检查集合中是否存在元素是正确的。否则,时间复杂度将远大于O(N)
。帮助表示赞赏。
解决方案
推荐阅读
- angular - 在具有反应式表单的 Angular 7 应用程序中,我如何修改此方法以使其仅清除表单组中的无效表单控件?
- css - 根据 body 标签类/属性在组件中应用不同的样式
- python - 如何用机械化捕捉超时
- sql - 在列中查找日期的准确性并将其复制并根据日期值的准确性分配给日期列
- sql-server - 数据库 B 和 C 中表中的所有行,只有数据库 A 中表中的唯一行
- c++ - C++ UBSAN 对派生对象产生误报
- python-3.x - 从数据框中写入多个 CSV 文件
- c# - 如何在 Jobject 中搜索节点
- python - 熊猫将唯一日期显示为重复
- java - 在输入具有最大和最小日期的情况下,Selenium 测试日期输入有问题