-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBitChangeWord.java
More file actions
71 lines (50 loc) · 1.49 KB
/
BitChangeWord.java
File metadata and controls
71 lines (50 loc) · 1.49 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
package swordPointOffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: Wenhang Chen
* @Description:
* @Date: Created in 9:16 4/26/2020
* @Modified by:
*/
public class BitChangeWord {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
int length = strs.length;
if (length == 0)
return res;
Map<String, Integer> map = new HashMap<>();
List<String> tempList;
for (int i = 0; i < length; i++) {
String temp = sort(strs[i]);
if (map.get(temp) == null) {
List<String> list = new ArrayList<>();
list.add(strs[i]);
map.put(temp, res.size());
res.add(list);
} else {
int index = map.get(temp);
tempList = res.get(index);
tempList.add(strs[i]);
}
}
return res;
}
// 桶排序
public String sort(String s) {
StringBuilder builder = new StringBuilder();
int[] buckets = new int[26];
int length = s.length();
for (int i = 0; i < length; i++)
buckets[s.charAt(i) - 'a']++;
for (int i = 0; i < 26; i++) {
while (buckets[i] > 0) {
builder.append((char) (i + 'a'));
buckets[i]--;
}
}
return builder.toString();
}
}