Python Tips:
- '.'.join([])
- re.split() or split()
- Counter() from collections
- defaultdict() from collections
- split the count first
- split domain, add all levels to a dict
- if exist, add counnt, else, add domain and count.
import re
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
# print(re.split(".| ", cpdomains[0]))
# print(re.findall(r"[\w']+", cpdomains[0]))
# print(re.split('\W', '900 google.ma-il.com'))
# print(cpdomains[0].replace('.',' ').split())
# domain_dict = {}
domain_dict = defaultdict(lambda: 0)
ans = []
for one_domain in cpdomains:
count, domain = one_domain.split()
domain = domain.split('.')
for i in range(len(domain)):
sub_domain = '.'.join(domain[i:])
domain_dict[sub_domain] += int(count)
# for sub_domain, value in domain_dict.items():
# ans.append(str(value) + " " + sub_domain)
# ans = ["{} {}".format(count, domain) for domain, count in domain_dict.items()]
ans = [f"{count} {domain}" for domain, count in domain_dict.items()]
return ans