[HashTable]049 Group Anagrams

  • 分类:HashTable

  • 考察知识点:HashTable 数组遍历

  • 最优解时间复杂度:O(mnlogn)*

49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

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

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

代码:

解法:

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        word_dict={}
        
        for word in strs:
            word_sort=str(sorted(word))
            if word_sort in word_dict:
                word_dict[word_sort].append(word)
            else:
                word_dict[word_sort]=[word]
        
        return list(word_dict.values())

讨论:

1.太简单了,完全不用动脑!

[HashTable]049 Group Anagrams_第1张图片
WechatIMG1631.jpeg

你可能感兴趣的:([HashTable]049 Group Anagrams)