/** * 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作为对象的key,map中不能直接使用,因为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); }