Voyz's Studio.

LeetCode算法笔记--字母异位词分组

字数统计: 182阅读时长: 1 min
2020/12/14 Share

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
/**
* @param {string[]} strs
* @return {string[][]}
*/
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
/**
* @param {string[]} strs
* @return {string[][]}
*/
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()]
};

CATALOG
  1. 1. LeetCode算法笔记–Day41
  2. 2. 49. Group Anagrams
    1. 2.1. 题目:
    2. 2.2. Analyze:
      1. 2.2.1. 方法一:分类法
    3. 2.3. My Answer:
      1. 2.3.1. 优化:引入哈希表
    4. 2.4. My Answer: