Skip to content

Commit 84f4469

Browse files
author
王俊超
committed
commit
1 parent 71a30d7 commit 84f4469

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.HashMap;
4+
import java.util.List;
5+
import java.util.Map;
6+
7+
/**
8+
* @author: wangjunchao(王俊超)
9+
* @time: 2018-09-28 15:33
10+
**/
11+
public class Solution {
12+
13+
public List<List<String>> groupAnagrams(String[] strs) {
14+
return groupAnagrams2(strs);
15+
}
16+
17+
/**
18+
* 算法原理:对字符串进行排序,相同类型的字符串排序后的字符串都是一样的
19+
*
20+
* @param strs
21+
* @return
22+
*/
23+
public List<List<String>> groupAnagrams1(String[] strs) {
24+
if (strs.length == 0) {
25+
return new ArrayList();
26+
}
27+
Map<String, List> ans = new HashMap<>();
28+
// 处理每一个字符串
29+
for (String s : strs) {
30+
char[] ca = s.toCharArray();
31+
// 对象字符串对应的字符数组进行排序,再转成排序后的字符串
32+
Arrays.sort(ca);
33+
String key = String.valueOf(ca);
34+
// 如果map中不包含已经排序后的字符串,那么就创建一个新容器要放入结果
35+
if (!ans.containsKey(key)) {
36+
ans.put(key, new ArrayList());
37+
}
38+
39+
// 结果放入对应的集合中
40+
ans.get(key).add(s);
41+
}
42+
return new ArrayList(ans.values());
43+
}
44+
45+
/**
46+
* 算法原理:统计每个字符出现的次数,然后使用#字符将每个字符出现的次数拼成一个字符串,
47+
* 相同类型的字符串通过上面的方式拼出来的字符串都是一样的
48+
*
49+
* @param strs
50+
* @return
51+
*/
52+
public List<List<String>> groupAnagrams2(String[] strs) {
53+
if (strs.length == 0) {
54+
return new ArrayList();
55+
}
56+
Map<String, List> ans = new HashMap<>();
57+
int[] count = new int[26];
58+
59+
for (String s : strs) {
60+
// 清零操作
61+
Arrays.fill(count, 0);
62+
for (char c : s.toCharArray()) {
63+
count[c - 'a']++;
64+
}
65+
66+
// 字符串拼接
67+
StringBuilder sb = new StringBuilder("");
68+
for (int i = 0; i < 26; i++) {
69+
sb.append('#');
70+
sb.append(count[i]);
71+
}
72+
String key = sb.toString();
73+
if (!ans.containsKey(key)) {
74+
ans.put(key, new ArrayList());
75+
}
76+
ans.get(key).add(s);
77+
}
78+
return new ArrayList(ans.values());
79+
}
80+
}

0 commit comments

Comments
 (0)