Soohan-Kim / Leetcode

0 stars 0 forks source link

[HW 4] Group Anagrams #49. #46

Open Soohan-Kim opened 3 months ago

Soohan-Kim commented 3 months ago

https://leetcode.com/problems/group-anagrams/description/

Soohan-Kim commented 3 months ago
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        allAngs = {}
        ret = []

        for s in strs:
            '''
            key = [0]*26

            for c in s:
                key[ord(c) - ord('a')] += 1
            key = tuple(key) # tuple can be used as key in dict since it is hashable
            '''

            # TC: O(n*mlogm), SC: O(n)
            key = ''.join(sorted(s))

            if key not in allAngs:
                allAngs[key] = [s]
            else:
                allAngs[key].append(s)

        for key in allAngs:
            ret.append(allAngs[key])

        return ret