仅记录自己刷题过程,顺便督促自我学习~
中等
题目描述
编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。
注意: 本题相对原题稍作修改
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[ ["ate","eat","tea"],
["nat","tan"],
["bat"]
]
提示:
- 所有输入均为小写字母。
- 不考虑答案输出的顺序。
我的实现
时间复杂度较高,所以当数组过长时候,超出时间限制了
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
let arr=[...new Set(strs.map(item=>item.split('').sort().join('')))]
//arr=['aet','ant','abt']
let res=[]
for(let i=0;i<arr.length;i++){
res[i]=[];
for(let j=0;j<strs.length;j++){
let temp=strs[j].split('').sort().join('');
if(arr[i]==temp){
res[i].push(strs[j]);
strs.splice(j,1);
j--
}
}
}
return res;
};
Map实现
/**
* @param {string} s
* @return {number}
*/
var groupAnagrams = function (strs) {
let hash = new Map();
for (let item of strs) {
// 字符串排序
const temp = item.split("").sort().join("");
if (hash.has(temp)) {
hash.get(temp).push(item);
} else {
hash.set(temp, [item]);
}
}
return [...hash.values()];
};