CODE/Algorithms & Data Structures

[LeetCode] Group Anagrams

BoriTea 2021. 10. 13. 11:06

 

 

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()