Day 10
Date: October 5, 2022 3:07 PM
LinkedIn: https://leetcode.cn/problems/subdomain-visit-count/
Title: 子域名访问计数
本题用到哈希查找,用到类似于C++中的map,在python中使用dict(字典)(相关用法附在代码后方)
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
dict = defaultdict(int) # defaultdict(int)则创建一个类似dictionary对象,里面任何的values都是int的实例,而且就算是一个不存在的key, d[key] 也有一个默认值,这个默认值是int类型值0
for s in cpdomains:
n, idx, cnt = len(s), 0, 0
while idx<n and s[idx] != ' ': # 找到最前面的数
idx+=1
cnt+= int(s[:idx]) # 0到idx-1
first, end = idx+1, n-1
while end>=first:
while end>=first and s[end] !='.':
end-=1
dict[s[end+1:]] +=cnt
end -=1
return [f'{v} {k}' for k, v in dict.items()] # 遍历字典 第一次获得元组的内容,第二次获得具体的值
字典的相关用法:
- 定义与修改
- 其中键和值都是python对象;用大括号{}创建字典
- 删除键或值(del、pop)
- del dict 删除字典
- del dict[key] 删除对应键的条目
- pop(key[,default]) #删除字典给定键key所对应的值,返回值为被删除的值。key值必须给出。否则,返回default值
- 函数
- cmp(dict1, dict2) #比较两个字典元素
- len(dict) #计算字典元素个数,即键的总数
- str(dict) #输出字典可打印的字符串表示
- type(variable) #返回输入的变量类型,如果变量是字典就返回字典类型
- dict.clear() #删除字典内所有元素
- dict.copy() #返回一个字典的浅复制
- dict.fromkeys(seq[val1,val2]) #创建一个新字典,以序列seq中元素作为字典的键,val为字典所有键对应的初始值
- dict.get(key, default = None) #返回指定键的值,如果值不在字典中返回default值
- dict.has_key(key) #如果键在字典dict中返回true,否则返回false
- dict.items() #以列表返回可遍历的(键,值)元组数组
- dict.keys() #以列表返回一个字典所有的键
- dict.setdefault(key, default=None) #和get()类似,但如果键不存在于字典中,将会添加键并将值设为default
- dict.update(dict2) #把字典dict2的键/值对更新到dict里
- dict.values() #以列表返回字典中的所有值
- popitem() #随机返回并删除字典中的一对键和值
- 其他
- defaultdict模块: defaultdict属于内建函数dict的一个子类,调用工厂函数
提供缺失的值- 如defaultdict(int)则创建一个类似dictionary对象,里面任何的values都是int的实例,而且就算是一个不存在的key, d[key] 也有一个默认值,这个默认值是int类型值0
- defaultdict模块: defaultdict属于内建函数dict的一个子类,调用工厂函数