Group Anagrams

Условие задачи (eng)

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.

Примеры

Input: strs = ["eat","tea","tan","ate","nat","bat"]

Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Решение

Развернуть
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = {}
        for i, word in enumerate(strs):
            group = ''.join(sorted(word))
            if group in groups:
                groups[group].append(i)
            else:
                groups[group] = [i]

        answer = []
        for group in groups:
            answer.append([strs[i] for i in groups[group]])

        return answer