题目地址
https://leetcode.cn/problems/group-anagrams/
题目描述
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [["bat"],["nat","tan"],["ate","eat","tea"]] 示例 2:
输入: strs = [""] 输出: [[""]] 示例 3:
输入: strs = ["a"] 输出: [["a"]]
|
解答
1 2 3 4 5 6 7 8 9 10 11 12
| const groupAnagrams = function (strs) { const map = new Map() for (let str of strs) { let array = Array.from(str) array.sort() let key = array.toString() let list = map.get(key) ? map.get(key) : [] list.push(str) map.set(key, list) } return Array.from(map.values()) }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| function xier(arr) { var interval = parseInt(arr.length / 2) while (interval > 0) { for (var i = 0; i < arr.length; i++) { var n = i while (arr[n] < arr[n - interval] && n > 0) { var temp = arr[n] arr[n] = arr[n - interval] arr[n - interval] = temp n = n - interval } } interval = parseInt(interval / 2) } return arr } const groupAnagrams = function (strs) { const map = {} for (let str of strs) { let array = Array.from(str) array = xier(array) let key = array.toString() let list = map[key] ? map[key] : [] list.push(str) map[key] = list } return Object.values(map) }
|