LeetCode49:Group Anagrams

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

LeetCode:链接

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

每个组合sort之后给一个key,将value值返回就可以了。

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        mydict = {}
        for str in strs:
            # 对str进行排序
            str_ = ''.join(sorted(str))
            if str_ in mydict:
                mydict[str_].append(str)
            # 定义的是列表形式
            else:
                mydict[str_] = [str]
        # 返回的是value值
        return mydict.values()

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/86212159