先将字符串按顺序转为key,然后收集到map中
最后将map转入result中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
var groupAnagrams = function (strs) { function formatStr(str) { return str.split("").sort().join(""); } const map = new Map(); const bankStrs = strs.slice(); bankStrs.forEach((o) => { const key = formatStr(o); if (map.has(key)) { map.get(key).push(o); } else { map.set(key, [o]); } }); const result = []; for (const key of map.keys()) { result.push(map.get(key)); } return result; };
|
优化写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
var groupAnagrams = function (strs) { const map = new Map(); strs.forEach((o) => { const key = o.split("").sort().join(""); if (map.get(key)) { map.get(key).push(o); } else { map.set(key, [o]); } }); return Array.from(map.values()); };
|
优化算法
采用计算字符频数生成hash
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
var groupAnagrams = function (strs) { const map = new Map(); for (const str of strs) { const count = Array(26).fill(0); for (const char of str) { count[char.charCodeAt(0) - 97]++; } const key = count.join("#"); if (map.has(key)) { map.get(key).push(str); } else { map.set(key, [str]); } } return Array.from(map.values()); };
|