题目来源:
https://leetcode.com/problems/anagrams/
题意分析:
给定一个字符串数组,将用相同字母(包括个数)组成的字符串放到一起。比如["eat", "tea", "tan", "ate", "nat", "bat"],返回
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]。所有的输入都是小写字母,返回的答案,里面的数组要按照字典序排序。
题目思路:
把字符串排好序的结果作为key,同一个key的字符串组成的队列作为value,构建一个字典。然后将字典的value排序,append到结果返回。
代码(python):
class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ d,ans= {},[] for i in strs: sortstr = ''.join(sorted(i)) if sortstr in d: d[sortstr] += [i] else: d[sortstr] = [i] #print(d) for i in d: tmp = d[i];tmp.sort() ans += [tmp] return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/4953824.html