字母异位词分组

先将字符串按顺序转为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
/**
* @param {string[]} strs
* @return {string[][]}
*/
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;
};
// groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]);

优化写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {string[]} strs
* @return {string[][]}
*/
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());
};
// console.log(`🚀 ~ groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]):`, groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));

优化算法
采用计算字符频数生成hash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {string[]} strs
* @return {string[][]}
*/
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());
};
// console.log(`🚀 ~ groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]):`, groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。