Leetcode刷题:811. Subdomain Visit Count

简单的字符串类型题目
Python做主要用到dict.get()和split()函数
version 1

class Solution(object):
    def subdomainVisits(self, cpdomains):
        """
        :type cpdomains: List[str]
        :rtype: List[str]
        """
        dict = {}
        res = []
        for d in cpdomains:
            #频次(times)和域名(domains)
            times = int(d.split(' ')[0])
            domain = d.split(' ')[1]
            subdomain = domain.split('.')
            dict[domain] = dict.get(domain,0) + times
            if len(subdomain) == 3:
                last_two = '.'.join(subdomain[1:])
                dict[last_two] = dict.get(last_two,0) + times
            if len(subdomain) >= 2:
                last_one = subdomain[-1]
                dict[last_one] = dict.get(last_one,0) + times
        #整理成结果
        for key in dict.keys():
            temp = str(dict[key]) + ' ' + key
            res.append(temp)
        return res

猜你喜欢

转载自blog.csdn.net/a529975125/article/details/79777631