leetcode49 字母异位词分组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012343179/article/details/89790201

思路:

1)字母异位词的判断方法一般是通过排序,但也有大神用质数表示26个字母,把字符串的各个字母相乘,这样可保证字母异位词的乘积必定是相等的。其余步骤就是用map存储,和别人的一致了。(这个用质数表示真的很骚啊!!!)

2)分组的话,用hashmap就行了。

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d={}
        for s in strs:
            s_sorted=''.join(sorted(s))
            if d.get(s_sorted)==None:
                d[s_sorted]=[s]
            else:
                d[s_sorted].append(s)
        return d.values()

猜你喜欢

转载自blog.csdn.net/u012343179/article/details/89790201