Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"]]
使用一个Map里面的键是经过排序的字符串,值是这类字符串在结果数组中的位置。
var groupAnagrams = function(strs) {
var num = strs.length;
var map = {};
var res = [];
var index = 0;
for(var i = 0;i < num;i++) {
var temp = strs[i].split("");
temp.sort();
temp = temp.join("");
if (map[temp]===undefined) {
map[temp] = index;
res.push([]);
res[index].push(strs[i]);
index++;
} else {
res[map[temp]].push(strs[i]);
}
}
return res;
};
网友评论