其他分享
首页 > 其他分享> > 49. Group Anagrams(js)

49. Group Anagrams(js)

作者:互联网

49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
题意:对数组项进行分类,具有相同字母的项为一组
代码如下:
/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) {
    var len=strs.length;
    var str=[];
    var res=new Map();
    for(var i=0;i<len;i++){
        //取键
        str=strs[i].split('').sort().join('');
        //存值
        if(!res.has(str)) 
            res.set(str,new Array())
        
        res.get(str).push(strs[i]);
    }
    return [...res.values()]
};

 

标签:Group,Anagrams,strs,tea,js,var,tan
来源: https://www.cnblogs.com/xingguozhiming/p/10428466.html