Original link: leetcode-cn.com/problems/gr…
Answer:
If you are not familiar with this problem, you can do 242. Valid letter heterotopic words, array counting, JavaScript, detailed comments.
- The final result is saved using a Map, which stores an array of grouped heterotopic words.
- Count each letter using an array of length 26, with the index value calculated from char. CodePointAt (0) – ‘a’. CodePointAt (0).
- The counted array is converted into a string, which is used as the key of the Map and stores the corresponding allobit string.
- Finally, convert the Map to an array and output the result.
/ * * *@param {string[]} strs
* @return {string[][]}* /
var groupAnagrams = function (strs) {
let resultMap = new Map(a);// Use Map to save the results
for (const str of strs) {
let keyArr = new Array(26).fill(0); // Use an array to count all letters
for (const char of str) {
// Calculate the difference between the letter and a. The difference will be between 0 and 25
const index = char.codePointAt(0) - 'a'.codePointAt(0);
// The corresponding number of letters +1
keyArr[index]++;
}
// Convert an array to a string that holds the result of the corresponding allobit
const key = JSON.stringify(keyArr);
// Store the allotopic words in the Map according to the corresponding key
resultMap.get(key)
? resultMap.get(key).push(str)
: resultMap.set(key, [str]);
}
// Convert the Map to an array and print the result
return [...resultMap.values()];
};
Copy the code