Problem Description#
Given a string array, please group the anagrams
together. The result list can be returned in any order.
An anagram
is a new word formed by rearranging the letters of a source word.
Example 1:
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Note:
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i] only contains lowercase letters
Approach#
- Strings that are anagrams of each other must contain the same letters, but in a different order.
- We can define a map structure to group the anagrams together under the same key.
- For this key, we can sort the string or calculate the sum of the charcode values of the string, or count the number of characters in the string.
Solution#
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
if (strs.length === 1) return [strs];
const m = new Map();
for (let i = 0; i < strs.length; i++) {
const temp = strs[i].split('').sort().join('');
// or const temp = Array.from(strs[i]).reduce((acc, curr) => acc + curr.charCodeAt(), 0);
if (m.has(temp)) {
m.set(temp, [...m.get(temp), strs[i]]);
} else {
m.set(temp, [strs[i]]);
}
}
return Array.from(m.values());
};