这个特定代码的空间和时间复杂度是多少

2024-04-24 12:21:37 发布

您现在位置:Python中文网/ 问答频道 /正文

字符串压缩

def com(s):
count = {}
char = []
fianl = []
for i in s:
    if i not in count:
        count[i] = 1

    else:
        count[i] +=1
#return count
for i ,j  in count.items():
    char.append(i)
    char.append(j)
for i in char:
    fianl.append(str(i))

return "".join(fianl)


s = "AAAAABBBBCCCC"
print(com(s))

第二,要确定字符串中的所有字符是否唯一

def uniq_c(s):
count = {}
for i in s:
    if i not in count:
        count[i] = 1
    else:
        count[i] +=1
#return count
for i in count.values():
    if i != 1:
        return False
return True


ar = "abcdee"
print(uniq_c(ar))

只是想知道它是否是O(n)的? 或任何其他建议,如果不是 谢谢


Tags: 字符串incomforreturnifdefcount
1条回答
网友
1楼 · 发布于 2024-04-24 12:21:37

从任何字典(哈希表)获取数据的平均时间复杂度为O(1),最差的时间复杂度为O(n),这是基于容器历史的非常罕见的情况。因此,一般将其视为O(1)时间复杂度。其余代码的复杂性非常明显

请阅读此official link以供参考

鉴于此,您现在可以自己推断复杂性

相关问题 更多 >