forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams_49.java
More file actions
89 lines (85 loc) · 3.32 KB
/
Copy pathGroupAnagrams_49.java
File metadata and controls
89 lines (85 loc) · 3.32 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.*;
/**
* 将字母异位词组合在一起
*/
public class GroupAnagrams_49 {
public static List<List<String>> groupAnagrams1(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
// 对字符串排序
char[] arr = str.toCharArray();
Arrays.sort(arr);
// 以排序后的字符串为key构建HashMap
String key = new String(arr);
List list = map.getOrDefault(key, new ArrayList<>());
list.add(str);
map.put(key, list);
}
return new ArrayList<>(map.values());
}
/**
* 失败:效率更低了
* @param strs
* @return
*/
public static List<List<String>> groupAnagrams2(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
// 统计每个字母出现的频率
Map<Character, Integer> countMap = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
int count = countMap.getOrDefault(str.charAt(i), 0);
count++;
countMap.put(str.charAt(i), count);
}
// 用每个字符加频率为key构建HashMap
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 26; i++) {
char c = (char) ('a' + i);
if (countMap.containsKey(c)) {
sb.append(c);
sb.append(countMap.get(c));
}
}
String key = sb.toString();
List list = map.getOrDefault(key, new ArrayList<>());
list.add(str);
map.put(key, list);
}
return new ArrayList<>(map.values());
}
/**
* 为什么还是比使用排序的方式耗时 -.-!
* @param strs
* @return
*/
public static List<List<String>> groupAnagrams3(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
// 统计每个字母出现的频率
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i) - 'a']++;
}
// 用每个字符加频率为key构建HashMap
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
sb.append((char) ('a' + i));
sb.append(count[i]);
}
}
String key = sb.toString();
List list = map.getOrDefault(key, new ArrayList<>());
list.add(str);
map.put(key, list);
}
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
String[] arr = {"chi","nip","lab","mud","fan","yak","kid","lox","joy","rob","cad","hug","ken","oaf","pus","hos","ton","any","sac","mid","nip","ron","tux","set","jug","axe","ago","sob","ode","dot","nit","pug","sue","new","rub","sup","ohs","ski","oaf","don","cob","kin","ark","gay","jay","bur","dot","eat","rca","wad","maj","luz","gad","dam","eon","ark","del","sin","tat"};
System.out.println(groupAnagrams1(arr));
System.out.println(groupAnagrams2(arr));
System.out.println(groupAnagrams3(arr));
}
}