Example: Group Anagrams - rFronteddu/general_wiki GitHub Wiki
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
To group anagrams together from a list of strings, we can use a hash map (or dictionary) where the keys are representations of the anagram groups (e.g., sorted strings or character counts) and the values are lists of strings that are anagrams of each other.
Approach:
- Sort Each String: For each string, sort the characters in the string. This sorted string will be the key in the hash map.
- Group by Key: Use the sorted string as a key and append the original string to the list of its corresponding key in the hash map.
- Collect Results: The values of the hash map will be the grouped anagrams.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap();
for (String s : strs){
String sortedS = sortString(s);
map.putIfAbsent (sortedS, new ArrayList<String>());
map.get (sortedS).add (s);
}
List<List<String>> res = new ArrayList();
for (String wordList : map.keySet()) {
res.add (map.get (wordList));
}
return res;
}
// return a string with characters alphabetically sorted
public String sortString (String s) {
char[] charArray = s.toCharArray();
Arrays.sort (charArray);
return String.valueOf(charArray);
}
}