from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagramGroup = defaultdict(list)
for word in strs:
countLetter = defaultdict(int)
for letter in word:
countLetter[letter] += 1
# a1e1t1 처럼 스트링으로 만들어서
newKey = ""
for key in sorted(countLetter):
newKey += str(key)
newKey += str(countLetter[key])
anagramGroup[newKey].append(word)
ans = []
for val in anagramGroup.values():
ans.append(val)
return ans
discussion을 보니까 다른 풀이도 존재했는데, 시간 차이는 별로 안나는듯! 이게 근데 더 보기좋다
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagramGroup = defaultdict(list)
for word in strs:
sortedWord = "".join(sorted(word))
anagramGroup[sortedWord].append(word)
ans = []
for val in anagramGroup.values():
ans.append(val)
return ans