LeetCode算法笔记–Day41
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”]
]
Analyze:
方法一:分类法
My Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
var groupAnagrams = function(strs) { let result = []; let basicWordArr = [];
strs.forEach((word,idx)=>{ let basicWord = word.split("").sort().join(""), basicIndex = basicWordArr.indexOf(basicWord); if(basicIndex >= 0){ result[basicIndex].push(word); }else{ basicWordArr.push(basicWord); result.push([word]); } })
return result; };
|
优化:引入哈希表
My Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
var groupAnagrams = function(strs) { let hash = new Map();
for (let i=0;i<strs.length;i++) { let basicWord = strs[i].split("").sort().join(); if(hash.has(basicWord)){ let currentWords = hash.get(basicWord); currentWords.push(strs[i]); hash.set(basicWord,currentWords); }else{ hash.set(basicWord,[strs[i]]) } }
return [...hash.values()] };
|