友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Runtime: 16 ms, faster than 22.85% of Java online submissions for Group Anagrams.
*
* Memory Usage: 40.4 MB, less than 96.49% of Java online submissions for Group Anagrams.
*/
public List<List<String>> groupAnagrams(String[] strs) {
if (Objects.isNull(strs) || strs.length == 0) {
return Collections.emptyList();
}
Map<String, List<String>> charsToStringsMap = new HashMap<>();
int[] count = new int[26];
for (String str : strs) {
Arrays.fill(count, 0);
char[] chars = str.toCharArray();
for (char aChar : chars) {
count[aChar - 'a']++;
}
StringBuilder builder = new StringBuilder(26 * 2);
for (int i : count) {
builder.append("#").append(i);
}
String key = builder.toString();
List<String> strings = charsToStringsMap.getOrDefault(key, new ArrayList<>());
strings.add(str);
charsToStringsMap.put(key, strings);
}
return new ArrayList<>(charsToStringsMap.values());
}
/**
* Runtime: 8 ms, faster than 96.90% of Java online submissions for Group Anagrams.
*
* Memory Usage: 41.1 MB, less than 95.32% of Java online submissions for Group Anagrams.
*/
public List<List<String>> groupAnagramsSort(String[] strs) {
if (Objects.isNull(strs) || strs.length == 0) {
return Collections.emptyList();
}
Map<String, List<String>> charsToStringsMap = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
List<String> strings = charsToStringsMap.getOrDefault(key, new ArrayList<>());
strings.add(str);
charsToStringsMap.put(key, strings);
}
return new ArrayList<>(charsToStringsMap.values());
}