[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)


 class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ref = {}
length = len(strs)
for str in strs:
word = "".join(sorted(str))
if word in ref:
ref[word] = ref[word] + [str]
else:
ref[word] = [str]
res = []
for key in ref:
l = ref[key]
l.sort()
res.append(l) return res

s

上一篇:asp.net MVC SignalR 与数据库 实时同步显示


下一篇:cocos2d-x高级学习