49. Group Anagrams【Python字典操作】

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.

熟练使用字典

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        tmp = {}
        for i in strs:
            sort_word = ''.join(sorted(i))
            if sort_word in tmp:
                tmp[sort_word] += [i]
            else:
                tmp[sort_word] = [i]

        return list(tmp.values())

 注意字典的创建,添加键和值得操作。

创建一个新的字典 a={}

创建未出现的键,并赋值 a[k] = [v]

对出现的键进行值得追加操作 a[k] += [v]

切记切记

你可能感兴趣的:(【LeetCode】刷题记录)