We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
49. 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
说明:
The text was updated successfully, but these errors were encountered:
解题思路:
/** * @param {string[]} strs * @return {string[][]} */ var groupAnagrams = function (strs) { let result = []; if (strs.length === 0) return result; let map = new Map(); for (const str of strs) { let arr = new Array(26).fill(0); for (let i = 0; i < str.length; i++) { const ascii = str[i].charCodeAt() - 97; arr[ascii]++; } const key = arr.join(""); if (map.has(key)) { map.set(key, [...map.get(key), str]); } else { map.set(key, [str]); } } for (const value of map.values()) { result.push(value); } return result; };
Sorry, something went wrong.
哈希表解
复杂度O(NKlogK), N 为 strs 长度,K 为 strs 中每个字符串的长度
O(NKlogK)
const len = strs.length; if (!len) return []; const ret = []; const map = new Map(); for (let i = 0; i < len; i++) { let newStr = strs[i].split('').sort().join(''); // 拆分排序合并后作为 key if (map.has(newStr)) { const old = map.get(newStr); old.push(strs[i]); map.set(newStr, old); } else { map.set(newStr, [strs[i]]); } } return Array.from(map.values());
No branches or pull requests
49. 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
说明:
The text was updated successfully, but these errors were encountered: