49. 字母异位词分组

49. 字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:

输入: strs = [""]
输出: [[""]]
示例 3:

输入: strs = ["a"]
输出: [["a"]]


解法

穷举法,时间复杂度为O(n^2),超时了.

class Solution:
    def wordIn(self, word1, word2):
        alphabel1=[0 for i in range(26)]
        alphabel2=[0 for i in range(26)]

        for i in word1:
            alphabel1[ord(i)-ord('a')]+=1
        for i in word2:
            alphabel2[ord(i)-ord('a')]+=1
        if alphabel1==alphabel2:
            return True
        else:
            return False
   

    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        visited = [0 for i in range(len(strs))]
        result = [[] for i in range(len(strs))]
        for i in range(len(strs)):
            if visited[i]:
                continue
            else:
                result[i].append(strs[i])
            for j in range(i + 1, len(strs)):
                visited[i] = 1

                if not visited[j]:
                    if self.wordIn(strs[i], strs[j]):
                        visited[j] = 1
                        result[i].append(strs[j])

                else:
                    continue
        result = [x for x in result if x != []]
        return result

python提供哈希表,也就是字典。
collections.defaultdict(list)
利用哈希表,key是一样的,因此就只需要添加值即可。

    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        mp=collections.defaultdict(list)
        for st in strs:
            key="".join(sorted(st))
            mp[key].append(st)
        return list(mp.values())