[leetcode]python3 算法攻略-字母异位词分组

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

方案一:对字符串排序

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

猜你喜欢

转载自blog.csdn.net/zhenghaitian/article/details/81257026
今日推荐