简体   繁体   English

查找字符串中每个字符出现的次数的复杂性

[英]complexity in finding the number of times each character is present in a string

input_string = "foobaarfoooobaaaarfo"
count_dict = {}
for char in input_string:
    try:
        count_dict[char]=count_dict[char]+1
    except:
        count_dict[char]=1
print(count_dict)

is this the best algorithm with complexity O(N) for the given problem statement 对于给定的问题陈述,这是否是复杂度为O(N)的最佳算法

Yes, O(n) is the best you can do. 是的, O(n)是您能做的最好的事情。

It is necessary to visit each character to count them all. 有必要拜访每个角色以数一数。

However, in terms of python implementation, you will probably get better performance, and more readable code using the specialized collection Counter : 但是,就python实现而言,您可以使用专门的Counter来获得更好的性能和更易读的代码:

from collections import Counter
input_string = "foobaarfoooobaaaarfo"
counter = Counter(input_string)
print(counter)

I agree that O(N) is the best you can do. 我同意O(N)是您能做的最好的事情。

I did a simplification for your program. 我为您的程序做了简化。 You do not have to use try and raise exception here. 您不必在此处使用try和引发异常。

input_string = "foobaarfoooobaaaarfo"
count_dict = {}
for char in input_string:
    count_dict[char] = count_dict.get(char, 0) + 1
print(count_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM