题目

解法
思路:空格和点是不同类型字符串的边界
s[:idx]的作用

class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
#使用哈希表记录每个子域名的计数
map={}
#遍历数组
for s in cpdomains:
#获取当前字符串的长度
n = len(s)
#每个字符串都是由数字加域名组成
#先去获取这个字符串的数字
#从0开始向后扫描到空格位置
idx = 0
#从前向后扫描到空格位置
while idx < n and s[idx] !=" ":#注意是判断空格不是空字符串
idx+=1
#截取出数字来
cnt = int(s[:idx])
#从后往前处理域名部分,直到处理完毕
start = idx+1
idx = n-1
#直到处理完毕
while idx >= start:
#每个域名由多个子域名组成
#通过.来截取
while idx >= start and s[idx] !=".":
idx -= 1
#获取当前子域名
cur = s[idx+1:]
#更新这个子域名的计数
map[cur] = map.get(cur, 0) + cnt
#idx继续向前移动
idx -=1
#从哈希表中构造出答案来
ans = []
for key in map:
#key是域名,map[key] 获取 value
ans.append(str(map[key]) + " " + key)
# 返回结果
return ans

348

被折叠的 条评论
为什么被折叠?



