BruteForce
1 | class Solution { |
Remarks:
- TC: $O(n^2\times L)$, SC: $O(n\times L)$. $L$ is the average length of each strings. VERY SLOW!
HashMap
1 | class Solution { |
Remarks:
- Key point: we can arrange the strings. Anagrams will become same after sorted, can have same hash value.
- TC: $O(n\times L \log L)$, SC: $O(n\times L)$
return new ArrayList<>(map.values());
has the type ofList<List<String>>
.map.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
is same as:1
2
3
4if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(str);