49. [✔][M]字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i]仅包含小写字母
题解:
思路:每个字符串处理后返回结果应该一样,那么处理函数就是构建1个26位数组,对应字符上+1,最后拼成1个字符串。注意join()不要用join(""),否则key为数字会有问题
/*
 * @lc app=leetcode.cn id=49 lang=typescript
 *
 * [49] 字母异位词分组
 */
// @lc code=start
function groupAnagrams(strs: string[]): string[][] {
    const encode = (s: string): string => {
        let record: number[] = new Array(26).fill(0);
        let base = 'a'.charCodeAt(0);
        for (const i of s) {
            record[i.charCodeAt(0) - base]++;
        }
        return record.join()
    }
    let map = new Map<string, string[]>();
    for (const str of strs) {
        let code = encode(str);
        if (map.has(code)) {
            let arr = map.get(code)!;
            arr.push(str);
            map.set(code, arr);
        } else {
            map.set(code, [str]);
        }
    }
    return [...map.values()];
};
// @lc code=end