第一种方法:排序后的字符串作为key
const groupAnagrams = (strs) => {
const obj = {};
let count = 1;
const res = [];
for(let i = 0; i < strs.length; i++) {
const cur = strs[i].split('').sort().join('');
if(obj[cur]){
res[obj[cur] - 1] = [...res[obj[cur] - 1], strs[i]];
} else {
obj[cur] = count++;
res.push([strs[i]])
}
}
return res;
};
第二种方法:计数作为key
const groupAnagrams = (strs) => {
const obj = {};
const aCharCodeAt = 'a'.charCodeAt();
for(let i = 0; i < strs.length; i++) {
const arr = new Array(26).fill(0);
for(let j = 0; j < strs[i].length; j++) {
arr[strs[i][j].charCodeAt() - aCharCodeAt]++;
};
const key = arr.join(',');
obj[key] ? obj[key].push(strs[i]) : obj[key] = [strs[i]];
}
return Object.values(obj);
}
来源: