49. Group Anagrams(Python3)

49. Group Anagrams(Python3)

题目

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

解题方案

思路:

  • 这道题的解决方案倒是没有什么特别的,主要是利用了排序和map
  • 这里要注意的是python的sorted函数对字符串排序后会将字符串分割成字符数组,需要用join()函数进行连接

代码:

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        res = []
        tmp = {}
        for i in range(len(strs)):
            key = "".join(sorted(strs[i]))
            if key in tmp:
                tmp[key].append(strs[i])
            else:
                tmp[key] = [strs[i]]
        for i in tmp:
            res.append(tmp[i])
        return res

你可能感兴趣的:(leetcode)