Last Commit: 2024-01-06 17:50:27

views:

Table of Content

49. Group Anagrams

source: https://leetcode.com/problems/group-anagrams/

Question

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

思路

一个anagrams内,其实排序后他们的值应该是相同的,所以可以用这个方法去区分。

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
    const cache = {};
    strs.forEach(str => {
        const key = Array.from(str).sort().join('');
        if (!cache[key]) cache[key] = [];
        cache[key].push(str);
    });
    return Object.keys(cache).reduce((acc, key) => {
        acc.push(cache[key]);
        return acc;
    }, []);
};

总结

要去理解题目中核心的定义是什么,然后再去想解。