LeetCode Hot 100:字母异位词分组

用排序 key 和 Map 分桶讲清字母异位词分组,并给出可复制的 JavaScript 实现。

这期讲 LeetCode Hot 100「字母异位词分组」。核心思路是给每个字符串生成稳定的 key,再用 Map 按 key 分桶;同一组字母异位词会落进同一个桶。
var groupAnagrams = function(strs) {
  const map = new Map();

for (const str of strs) {
    const key = str.split('').sort().join('');

if (!map.has(key)) {
      map.set(key, []);
    }

map.get(key).push(str);
  }

return Array.from(map.values());
};
时间复杂度是 O(n * k log k),其中 n 是字符串数量,k 是最长字符串长度;空间复杂度是 O(n * k)
来源:

Related content

  • Sign in to comment.
More from this channel