leetcode专题训练 49. Group Anagrams

1.最开始的想法,如果遍历所有字符串,如果该字符串的字母异位词已经被扫到过,也就是Count数组中有一样的Counter,那么就把这个归入到之前的那个词所在的那个列表中,未扫到过,就把这个词归入到新的列表中,并把该词的Counter存入到Count列表中。然后超时了。

from collections import Counter

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        Count = []
        result = []
        for s in strs:
            flag = 0
            cou = Counter(s)
            for i in range(len(Count)):
                if Count[i] == cou:
                    flag = 1
                    result[i].append(s)
                    break
            if not flag:
                result.append([s])
                Count.append(cou)
            
        return result

2.然后我改进了一下我的算法,不和Count中的所有Counter比较,只用和Count中与cou长度相同的Counter比较。然后又超时了。

from collections import Counter
import numpy as np

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        Count = [[]]*27
        result = []
        index = [[]]*27
        now = 0
        for s in strs:
            flag = 0
            cou = Counter(s)
            l = len(cou)
            l1 = len(Count[l])
            for i in range(l1):
                if Count[l][i] == cou:
                    flag = 1
                    result[index[l][i]].append(s)
                    break
            if not flag:
                result.append([s])
                index[l].append(now)
                now += 1
                Count[l].append(cou)
            
        return result

3.然后我看了题解,发现了一个巨无比好用的数据结构defaultdict。
defaultdict接受一个工厂函数作为参数,如下来构造:

dict =defaultdict( factory_function)

这个factory_function可以是list、set、str等等,作用是当key不存在时,返回的是工厂函数的默认值,比如list对应[ ],str对应的是空字符串,set对应set( ),int对应0。(defaultdict介绍转载自https://www.jianshu.com/p/bbd258f99fd3)
有了这个数据结构之后,只用以下短短几行代码就可以解决问题了。需要注意的是,dict的关键字必须是不可变的(可哈希的),比如int, str, tuple, bool,所以在将Counter存入dict之前,要把Counter转化为不可变的tuple。
我之前两个方法超时的原因应该就是键值没有用哈希的方式进行排列检索,而dict数据结构会自动用哈希的方式排列检索,就不会超时了。

from collections import Counter
from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic =defaultdict(list)
        for s in strs:
            cou = Counter(s)
            counter_new = sorted(cou.items())
            dic[tuple(counter_new)].append(s)
        return dic.values()

我爱学习,生病了也要学习。行动是最好的降低焦虑的方式。兴趣是最好的导师。

发布了201 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/100780137