Skip to content

Commit 90a3376

Browse files
committed
feat: solve group anagrams
1 parent 6bbd720 commit 90a3376

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

group-anagrams/GangBean.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public List<List<String>> groupAnagrams(String[] strs) {
3+
/**
4+
1. understanding
5+
- grouping the anagrams together, and return groups
6+
2. strategy
7+
- anagram group's identity: same characters with same counts
8+
- so, transform each strs to character and count hashtable, called 'id'.
9+
- if groups contains strs's 'id', then append
10+
- return values list
11+
3. complexity
12+
- time: O(N * L) where, N is the length of array strs, and L is the max length of each str
13+
- space: O(N * L)
14+
*/
15+
Map<Map<Character, Integer>, List<String>> groups = new HashMap<>();
16+
for (String word: strs) {
17+
Map<Character, Integer> id = idOf(word);
18+
List<String> group = groups.getOrDefault(id, new ArrayList<>());
19+
group.add(word);
20+
groups.put(id, group);
21+
}
22+
23+
// System.out.println(groups);
24+
List<List<String>> ret = new ArrayList<>();
25+
ret.addAll(groups.values());
26+
return ret;
27+
}
28+
29+
private Map<Character, Integer> idOf(String word) {
30+
Map<Character, Integer> id = new HashMap<>();
31+
for (char c: word.toCharArray()) {
32+
id.put(c, id.getOrDefault(c, 0) + 1);
33+
}
34+
return id;
35+
}
36+
}
37+

0 commit comments

Comments
 (0)