Skip to content

Commit

Permalink
feat: solve group anagrams
Browse files Browse the repository at this point in the history
  • Loading branch information
GangBean committed Jan 5, 2025
1 parent 6bbd720 commit 90a3376
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions group-anagrams/GangBean.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
/**
1. understanding
- grouping the anagrams together, and return groups
2. strategy
- anagram group's identity: same characters with same counts
- so, transform each strs to character and count hashtable, called 'id'.
- if groups contains strs's 'id', then append
- return values list
3. complexity
- time: O(N * L) where, N is the length of array strs, and L is the max length of each str
- space: O(N * L)
*/
Map<Map<Character, Integer>, List<String>> groups = new HashMap<>();
for (String word: strs) {
Map<Character, Integer> id = idOf(word);
List<String> group = groups.getOrDefault(id, new ArrayList<>());
group.add(word);
groups.put(id, group);
}

// System.out.println(groups);
List<List<String>> ret = new ArrayList<>();
ret.addAll(groups.values());
return ret;
}

private Map<Character, Integer> idOf(String word) {
Map<Character, Integer> id = new HashMap<>();
for (char c: word.toCharArray()) {
id.put(c, id.getOrDefault(c, 0) + 1);
}
return id;
}
}

0 comments on commit 90a3376

Please sign in to comment.