[LeetCode]题解(python):049-Groups Anagrams


题目来源


https://leetcode.com/problems/anagrams/

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

题意分析


Input: a list of words

Output: the groups

Conditions: 如果含字母一样,那么归为一组,同时组内要以字典序递增的顺序


题目思路


利用字典来分组,因为一个word经过排序后,如果一样则属于一个分组,另外组内升序直接sort即可


AC代码(Python)


 1 class Solution(object):
 2     def groupAnagrams(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: List[List[str]]
 6         """
 7         ref = {}
 8         length = len(strs)
 9         for str in strs:
10             word = "".join(sorted(str))
11             if word in ref:
12                 ref[word]  = ref[word] + [str]
13             else:
14                 ref[word] = [str]
15         res = []
16         for key in ref:
17             l = ref[key]
18             l.sort()
19             res.append(l)
20         
21         return res

s

原文地址:https://www.cnblogs.com/loadofleaf/p/5093561.html