Python 解leetcode:49. Group Anagrams

  • 题目描述:给出一个由字符串组成的数组,把数组中字符串的组成字母相同的部分放在一个数组中,并把组合后的数组输出;

  • 思路:

  1. 使用一个字典,键为数组中字符串排序后的部分,值为排序后相同的字符串组成的列表;
  2. 遍历数组完成后,返回字典的值就可以了。
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        ret = {}
        for s in strs:
            ts = ''.join(sorted(s))
            if ret.get(ts):
                ret[ts].append(s)
            else:
                ret[ts] = [s]
        return ret.values()