File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments