Group Anagrams | LeetCode Medium Challenge Day 38
Question Overview:
Given an array of strings, the task is to group the strings that are anagrams of each other. An anagram is a word formed by rearranging the letters of another, such as “listen” and “silent.”
领英推荐
Explanation:
To group the anagrams, we can use a hashmap (Map<String, List<String>>) where the key is a sorted version of the string, and the value is a list of strings that are anagrams of that key. Here’s how the solution works:
1. Sorting Strings as Keys: For each string in the input array, we sort its characters. This sorted string serves as the key in our hashmap, as all anagrams will have the same sorted version.
2. Storing Anagrams: If the sorted version of the string (key) doesn’t exist in the map, we create a new entry. Then, we add the original string to the list associated with that key.
3. Returning the Result: Finally, we return all the values in the hashmap as a list of lists, where each list contains grouped anagrams.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(s);
}
return new ArrayList<>(map.values());
}
}