数据结构【字符串、哈希表】| leetcode 811. 子域名访问计数(中等)

代码链接:https://leetcode.cn/problems/subdomain-visit-count/solution/zi-yu-ming-fang-wen-ji-shu-by-leetcode/

哈希映射:对于包含一个 . 的域名 x.y,我们需要统计的是 x.yy;对于包含两个 . 的域名 a.b.c,我们需要统计的是 a.b.cb.cc。在统计这些字符串时,我们可以使用哈希映射(HashMap)。统计结束之后,我们遍历哈希映射并输出结果。

class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        hashmap = {}
        
        for domain in cpdomains:
            num = int(domain.split()[0])
            frags = domain.split()[1].split(".")  # "9001 discuss.leetcode.com"

            for i in range(len(frags)):
                if '.'.join(frags[i:]) in hashmap:
                    hashmap['.'.join(frags[i:])] += num
                else:
                    hashmap['.'.join(frags[i:])] = num
        return ["{} {}".format(value, key) for key, value in hashmap.items()]

            # if domain[-1] in hashmap:                # "9001 leetcode.com"
            #     hashmap[domain[-1]] += num
            # else:
            #     hashmap[domain[-1]] = num
            
            # if '.'.join(domain[-2:]) in hashmap:
            #     hashmap['.'.join(domain[-2:])] += num
            # else:
            #     hashmap['.'.join(domain[-2:])] = num

            # if len(domain) == 3:
            #     if '.'.join(domain) in hashmap:
            #         hashmap['.'.join(domain)] += num
            #     else:
            #         hashmap['.'.join(domain)] = num
        
        # res = []
        # for key, value in hashmap.items():
        #     res.append(str(value)+' '+ key)
        # return res

复杂度分析

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N 是数组 cpdomains 的长度,这里假设 cpdomains 中每个元素的长度都是常数级别的。
  • 空间复杂度: O ( N ) O(N) O(N),用于存储哈希映射。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值