码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-01-01 18:58:13      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


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

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!