LeetCode Medium: 49. Group Anagrams
一、题目
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
给定一组字符串,相同的分组
二、思路
采用字典,首先采用类似于one-hot编码,将26个字母作为基体,对于每个字符串,相应位置的字母做计数操作,如果字符串字母组成相同但是顺序不同,但是编码之后的形式肯定是相同,用编码后的形式作为key,对应的字符串作为value。
三、代码
#coding:utf-8 import collections class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ resdic = collections.defaultdict(list) #这句代码很重要,在Python中如果访问字典中不存在的键,会引发KeyError异常。因此,可以采用collections.defaultdict来初始化字典。defaudict初始化函数接受一个类型作为参数,当访问不存在的key时,可以实例化一个值作为默认值,从而省去了使用dict时需要判断key是否存在的问题。试过,如果不这样做的话会报错 dic = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25} for str in strs: count = [0]*26 for c in str: count[dic[c]] += 1 resdic[tuple(count)].append(str) print('me:',list(resdic.values())) return list(resdic.values()) def groupAnagrams1(self,strs): ans = collections.defaultdict(list) for s in strs: count = [0] * 26 for c in s: count[ord(c) - ord('a')] += 1 ans[tuple(count)].append(s) print('not me:',list(ans.values())) return list(ans.values()) if __name__ == '__main__': ss = Solution() a = ["eat","tea","tan","ate","nat","bat"] ss.groupAnagrams(a) ss.groupAnagrams1(a)
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢