给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

    1. 输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
    2. 输出:
    3. [
    4. ["ate","eat","tea"],
    5. ["nat","tan"],
    6. ["bat"]
    7. ]
    1. /**
    2. * 哈希表 + 排序
    3. * 时间复杂度:O(n*k log k)
    4. * 空间复杂度:O(n*k)
    5. */
    6. var groupAnagrams = function (strs) {
    7. const map = {}
    8. for (const str of strs) {
    9. const key = str.split('').sort().join('')
    10. if (map[key]) {
    11. map[key].push(str)
    12. } else {
    13. map[key] = [str]
    14. }
    15. }
    16. return Object.keys(map).map((key) => map[key])
    17. }