Last active
April 1, 2018 07:54
-
-
Save willwangcc/1fc73c6e2f2d1d6b38c1aec605d5f9f2 to your computer and use it in GitHub Desktop.
Elegant code: 1. string.join() 2. "{} {}".format(x, y)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Time: O(n) | |
# Space: O(n) | |
# Before vs After | |
##################################### | |
## After | |
##################################### | |
class Solution(object): | |
def subdomainVisits(self, cpdomains): | |
ans = collections.Counter() | |
for domain in cpdomains: | |
count, domain = domain.split() | |
count = int(count) | |
frags = domain.split('.') | |
for i in xrange(len(frags)): | |
ans[".".join(frags[i:])] += count ## string.join() | |
return ["{} {}".format(ct, dom) for dom, ct in ans.items()] # format | |
##################################### | |
## Before | |
##################################### | |
from collections import defaultdict | |
class Solution(object): | |
def subdomainVisits(self, cpdomains): | |
""" | |
:type cpdomains: List[str] | |
:rtype: List[str] | |
""" | |
# init: hashmap | |
ans = defaultdict(int) | |
# interate | |
for each in cpdomains: | |
count, domain = each.split(" ") | |
count = int(count) | |
element = domain.split(".") # | |
ans[domain] += count | |
left = '' | |
for i in range(len(element)-1): | |
left += element[i] + '.' | |
temp = domain[len(left):] | |
ans[temp] += count | |
res = [] | |
for d,c in ans.items(): | |
format_ans = str(c) + " " + d | |
res.append(format_ans) | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment