49字母异位词分组

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/group-anagrams 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution 1

哈希(排序)

class Solution:
    def groupAnagrams(self, strs: [str]) -> [[str]]:
        def hashAnagrams(word):
            temp = list(word)
            temp.sort()
            result = ""
            for char in temp:
                result += char
            return result
        result = {}
        for word in strs:
            if hashAnagrams(word) in result.keys():
                result[hashAnagrams(word)].append(word)
            else:
                result[hashAnagrams(word)] = [word]
        result = list(result.values())
        return result

Solution 2

哈希(计数)

class Solution:
    def groupAnagrams(self, strs: [str]) -> [[str]]:
        def hashAnagrams(word):
            count = [0]*26
            for char in word:
                count[ord(char)-ord('a')] += 1
            result = "#"
            for num in count:
                result += str(num)
                result += '#'
            return result
        result = {}
        for word in strs:
            if hashAnagrams(word) in result.keys():
                result[hashAnagrams(word)].append(word)
            else:
                result[hashAnagrams(word)] = [word]
        result = list(result.values())
        return result