49. Group Anagrams
https://leetcode.com/problems/group-anagrams/submissions/
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.
Thoughts
给一些单词,让把出现相同字符的单词放在一组。判断是否permutation除了用count map检测每个元素是否都在, 还可以用 sorting配合hash table。
Code
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
m = collections.defaultdict(list)
for s in strs:
# m[''.join(sorted(s))].append(s)
cnt = [0] * 26
for c in s:
cnt[ord(c) - ord('a')] += 1
m[tuple(cnt)].append(s)
return m.values()Analysis
时间复杂度O(nlgn).
Last updated
Was this helpful?