字母异位词

26 阅读1分钟

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

示例 1:

输入:  

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

输出:

[["bat"],["nat","tan"],["ate","eat","tea"]]

解释:

  • 在 strs 中没有字符串可以通过重新排列来形成 "bat"
  • 字符串 "nat" 和 "tan" 是字母异位词,因为它们可以重新排列以形成彼此。
  • 字符串 "ate" ,"eat" 和 "tea" 是字母异位词,因为它们可以重新排列以形成彼此。
var groupAnagrams = function(strs) {
    const map = new Map();          // 用来保存“签名 → 同组字符串列表”
    for (let str of strs) {         // 遍历每个输入字符串
        let array = Array.from(str) // 把字符串拆成字符数组
        array.sort();               // 按字母顺序排序,得到“签名”
        let key = array.toString(); // 把排序后的数组转成字符串作为 key
        let list = map.get(key) ? map.get(key) : new Array(); // 取旧列表或新建
        list.push(str);             // 把当前字符串放进对应列表
        map.set(key, list);         // 写回 map
    }
    return Array.from(map.values()); // 把 map 中的所有列表抽出来,组成二维数组
};

map常见使用

操作API
放/改set
get
有无has
delete / clear
大小size
遍历for-of / forEach / ...
转数组[...map]
转对象Object.fromEntries(map)

解析:JavaScript的解法比较简洁,遍历给出的数组,把每个数组对象即是字符串转成数组-排序,再转成字符串,做一个map映射。通过map.get去遍历,通过list存找出来的字符串。使用key和list存在map里。返回数据的时候,转成数组。