题解 | #使用字典计数#

使用字典计数

https://www.nowcoder.com/practice/74f7e7f2344f4754bc56d862838cbfc3

这里有个点可以学习下


#方法一
# ls1 = list(input())
# ls2 = [ls1.count(i) for i in ls1]
# print(dict(zip(ls1,ls2)))
#方法二
# from collections import Counter
# ls1 = input()
# print(dict(Counter(ls1)))
#方法三:
# ls1 = list(input())
# dict1 = {}
# for i in ls1:
#     if i in dict1:
#         continue
#     dict1[i] = ls1.count(i)
# print(dict1)
# #方法四
# ls1 = list(input())
# dict1 = {}
# for i in ls1:
#     if i in dict1:
#         dict1[i] += 1
#     else:
#         dict1[i] = 1
# print(dict1)
#方法五
# ls1 = list(input())
# dict1 = {}
# for i in ls1:
#     dict1[i] = dict1.get(i,0)+1
# print(dict1)
全部评论
关于第三种方法中list.count()用法:https://www.runoob.com/python/att-list-count.html
3 回复 分享
发布于 2023-03-18 22:30 山东
从O(N^2)优化到了O(N),一题多解好棒!!
1 回复 分享
发布于 2023-08-05 20:11 安徽
太牛了吧!!!学到了哈哈 不过第三种方法不要‘if i in dict1: continue’应该也可以吧,字典本身就会去重的
1 回复 分享
发布于 2023-03-03 22:28 湖北

相关推荐

评论
168
12
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务