algorighm/top-interview-leetcode150/hash-table/49字母异位词分组.js

104 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-interview-150
* @param {string[]} strs
* @return {string[][]}
*/
const groupAnagrams = function (strs) {
};
/*
题目要求我们对字符串中的异位词分组首先创建一个map遍历strs中的所有字符串查看它是否是map中某一个key的异位词如果是的话
把它插入到这个key对应的数组中去如果不是的话表明他是一个新的字符串所以在map中创建一个映射用来收集它的异位词
*/
function f1(strs) {
const map = new Map();
const result = [];
for (let i = 0; i < strs.length; i++) {
let found = false;
// 查找 map 中是否有对应的异位词
for (const [key, value] of map) {
if (key.length === strs[i].length && isAnagram(strs[i], key)) {
value.push(strs[i]); // 如果是异位词,加入现有的数组
found = true; // 标记找到
break; // 找到就停止遍历
}
}
// 如果没有找到,就创建新的异位词组
if (!found) {
map.set(strs[i], [strs[i]]);
}
}
// 将 map 中的所有异位词数组收集到 result
for (const [, value] of map) {
result.push(value);
}
return result;
}
/*
利用字符序来判断异位词
*/
function f2(strs) {
const map = new Map();
const result = [];
// 遍历所有字符串
for (let i = 0; i < strs.length; i++) {
// 排序字符串,得到标准化形式
const sortedStr = strs[i].split('').sort().join('');
// 如果 map 中已经有这个排序后的字符串,就将当前字符串加入对应的数组
if (map.has(sortedStr)) {
map.get(sortedStr).push(strs[i]);
} else {
// 如果没有,创建新的映射
map.set(sortedStr, [strs[i]]);
}
}
// 将 map 中的所有异位词数组收集到 result
for (const [, value] of map) {
result.push(value);
}
return result;
}
// 检测两个词是否是异位词
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const charCounts = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
charCounts[s.charCodeAt(i) - 97]++;
charCounts[t.charCodeAt(i) - 97]--;
}
return charCounts.every((count) => count === 0);
}
/*
利用一个数组来储存str的字符计数如果计数相同就判断它们是异位词这个代码巧妙之处是直接把数组作为key,本质就是调用数组的toString()
之后拿这个string作为对象的keymap中不能直接使用因为map是通过引用来判断的即使内容一样也会判为不同的str如果非要要用map可以
使用 String(count)作为map的key
*/
function f3(strs) {
// eslint-disable-next-line no-new-object
const map = new Object();
for (const s of strs) {
const count = new Array(26).fill(0);
for (const c of s) {
count[c.charCodeAt() - 'a'.charCodeAt()]++;
}
// eslint-disable-next-line no-unused-expressions
map[count] ? map[count].push(s) : map[count] = [s];
}
return Object.values(map);
}