Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
There is no string in strs that can be rearranged to form "bat".
The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Create a map to group the anagrams, where the key is the sorted string, and the value is a list of original strings.
Map<String, List<String>> anagramsMap = new HashMap<>();
// Iterate over each string in the array.
for (String str : strs) {
// Convert the string to a character array and sort it.
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
// Create a new string from the sorted character array.
String sortedStr = String.valueOf(charArray);
// If the sorted string key is not present in the map, initialize the list.
// Then add the original string to the list associated with the sorted string key.
// anagramsMap.computeIfAbsent(sortedStr, key -> new ArrayList<>()).add(str);
anagramsMap.putIfAbsent(sortedStr, new ArrayList<>());
anagramsMap.get(sortedStr).add(str);
}
return new ArrayList<>(anagramsMap.values());
}
}
Comments
Post a Comment