luzhipeng aea6437 May 29, 2019
0 contributors

### Users who have contributed to this file

103 lines (80 sloc) 2.39 KB

## 题目地址

https://leetcode.com/problems/group-anagrams/description/

## 题目描述

``````Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.
``````

## 思路

```var groupAnagrams = function(strs) {
const hashTable = {};

function sort(str) {
return str
.split("")
.sort()
.join("");
}

// 这个方法需要排序，因此不是很优，但是很直观，容易想到
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
const key = sort(str);
if (!hashTable[key]) {
hashTable[key] = [str];
} else {
hashTable[key].push(str);
}
}

return Object.values(hashTable);
};```

• 桶排序

## 代码

```/*
* @lc app=leetcode id=49 lang=javascript
*
* [49] Group Anagrams
*/
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
// 类似桶排序

let counts = [];
const hashTable = {};
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
counts = Array(26).fill(0);
for (let j = 0; j < str.length; j++) {
counts[str[j].charCodeAt(0) - "a".charCodeAt(0)]++;
}
const key = counts.join("");
if (!hashTable[key]) {
hashTable[key] = [str];
} else {
hashTable[key].push(str);
}
}

return Object.values(hashTable);
};```
You can’t perform that action at this time.