Skip to content

Latest commit

 

History

History
22 lines (16 loc) · 877 Bytes

49.-group-anagrams.md

File metadata and controls

22 lines (16 loc) · 877 Bytes

49. Group Anagrams

  • Medium

  • Given an array of strings strs, group the anagrams together. You can return the answer in any order.

    An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Analysis

For two words to be anagrams, their sorted version will be equal. For example "bat" and "tab" will both become "abt" after sorted. Therefore we can use the sorted version as keys for an dicitionary and use that dictionary to record the strings.

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups=defaultdict(list)
        for i in strs:
            temp="".join(sorted(i))
            groups[temp].append(i)
        return groups.values()