Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Solutions:
(1) sort equal, create a map with sorted array as key (ans.put(key, new ArrayList()), ans.get(key).add(s))
Time: O(nklogk) sort(O(klogk)) n times
Java:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String key = String.valueOf(ca);
if (!ans.containsKey(key)) ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}
// https://leetcode.com/problems/group-anagrams/solution/
Python: collections.defaultdict
class Solution(object):
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
# https://leetcode.com/problems/group-anagrams/solution/
(2) categorize by the count of 26 charaters
use the count as the key of the map
Time : O(NK), where N is the length of strs, and K is the maximum length of a string in strs

Java:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();
int[] count = new int[26];
for (String s : strs) {
Arrays.fill(count, 0);
for (char c : s.toCharArray()) count[c - 'a']++;
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 26; i++) {
sb.append('#');
sb.append(count[i]);
}
String key = sb.toString();
if (!ans.containsKey(key)) ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}
// https://leetcode.com/problems/group-anagrams/solution/
Python:
class Solution:
def groupAnagrams(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)
return ans.values()
# https://leetcode.com/problems/group-anagrams/solution/
字符串变位词分组问题的解决方案
博客围绕字符串变位词分组问题展开,变位词是通过重新排列不同单词或短语字母形成的。给出两种解决方案,一是以排序后的数组为键创建映射,时间复杂度为O(nklogk);二是按26个字符的计数分类,以计数为键,时间复杂度为O(NK),并给出Java和Python示例。
563

被折叠的 条评论
为什么被折叠?



