【Leetcode_总结】49. 字母异位词分组 - python

Q:

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

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

链接:https://leetcode-cn.com/problems/group-anagrams/description/

思路:因为是易位词,因此排序后的词顺序是相同的,因此对排序后的词通过hash map进行保存,保存的是其在res中的位置,然后将后续的值插入就可以了

代码:

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        strs_map = {}
        result = []
        for i in strs:
            string = ''.join(sorted(i))
            if string not in strs_map:
                strs_map[string] = len(result)
                result.append([i])
            else:
                result[strs_map[string]].append(i)
        return result

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/85806679
今日推荐