Group Anagrams

原题信息

题号49,难度中等,涉及考点:数组、Map

题目

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.

示例

Example 1:

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

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

备注

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lower-case English letters.

分析

Anagram (回文构词法) 是指打乱字母顺序从而得到新的单词,回文构词法有个特点:单词里的字母种类和数目没有改变,只是改变字母的排列顺序,因此,将几个单词按照字母顺序排序后,若相等,则属于同一组anagrams。

一开始的思路:拷贝一份数组,然后排序,相同的放在hash表里有相同的坐标,返回坐标相同的数组元素,后来被启发可以绑定key值,根据相同key值返回。

js题解

作者:barba-lee
链接:https://leetcode-cn.com/problems/group-anagrams/solution/shi-yong-mapsan-xing-jie-jue-yong-shi-ji-i8ly/

思路

1. 定义map存储
2. 字符串转数组->排序->转字符串为key(将所有异位词排序为同一单词,作为key)
3. 根据key插入map
4. map传数组输出

题解

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) { let map = new Map(); strs.forEach((str) => { const key = str.split("").sort().join(""); map.has(key) ? map.get(key).push(str) : map.set(key, [str]); }); return Array.from(map.values());
};

 

posted @ 2021-04-17 11:30  告别海岸  阅读(96)  评论(0)    收藏  举报