标签:count Matter cas plain case solution 初始 get 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:
这道题就是用每个单词sorted以后做key,然后loop through。最后的时间复杂度是O(nmlogm), 空间复杂度是O(nm)。但可以进一步优化成O(nm), 就是不用sorted, 而是用一个O(m)的方法替代。注意的点是:1)list是不能做key的,要变成tuple。2)到得到dict的key,就用values() 3)如果想要初始一个value是list的dict,用collections.defaultdict(list) 这样就不用一直判断key存不存在,然后不存在要初始一个list。
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if str is None: return None
d = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord(‘a‘)] += 1
d[tuple(count)].append(s)
return list(d.values())
sorted的解法
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if str is None: return None
d = {}
for s in strs:
key = tuple(sorted(s))
d[key] = d.get(key, []) + [s]
return list(d.values())
这里面注意可以用get,如果为空就初始一个[],然后用+ 去做append
最plain的写法
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if not strs: return None
str_map = dict()
for a_str in strs:
sorted_s = ‘‘.join(sorted(a_str))
if sorted_s not in str_map:
str_map[sorted_s] = [a_str]
else:
str_map[sorted_s].append(a_str)
res = [v for v in str_map.values()]
return res
标签:count Matter cas plain case solution 初始 get anagrams
原文地址:https://www.cnblogs.com/codingEskimo/p/12651261.html