Problem
Solution
Two strings are anagrams if the frequencies of appearing alphabets are the same.
Make a dictionary, where the keys are tuples of alphabet(a-z) frequencies. The values are the strings in the given list.
When I initiated an dictionary and used append function with a new key, it gave a KeyError. To avoid this, use defaultdict function and pass list as parameter. Then a defaultdict is created with the values that are list, and I can use append with new keys.
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
from collections import defaultdict
result = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c)-ord('a')] += 1
result[tuple(count)].append(s)
return result.values()
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[LeetCode] Add Two Numbers (0) | 2021.10.17 |
---|---|
[LeetCode] Trapping Rain Water (0) | 2021.10.15 |
[Coderust] Find Maximum in Sliding Window (0) | 2021.10.13 |
[Coderust] Binary Search on Sorted Array (0) | 2021.10.11 |
[LeetCode] Longest Palindromic Substring (0) | 2021.10.11 |