49.字母异位词分组

2024/3/23

# Heading

    49.字母异位词分组 (opens new window)

    Tags: algorithms amazon bloomberg facebook uber yelp hash-table string

    Langs: c cpp csharp dart elixir erlang golang java javascript kotlin php python python3 racket ruby rust scala swift typescript

    • algorithms
    • Medium (67.90%)
    • Likes: 1857
    • Dislikes: -
    • Total Accepted: 657.2K
    • Total Submissions: 967.4K
    • Testcase Example: '["eat","tea","tan","ate","nat","bat"]'

    给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

    字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

     

    示例 1:

    输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

    示例 2:

    输入: strs = [""]
    输出: [[""]]
    

    示例 3:

    输入: strs = ["a"]
    输出: [["a"]]

     

    提示:

    • 1 <= strs.length <= 104
    • 0 <= strs[i].length <= 100
    • strs[i] 仅包含小写字母
    /*
     * @lc app=leetcode.cn id=49 lang=javascript
     *
     * [49] 字母异位词分组
     */
    
    // @lc code=start
    /**
     * @param {string[]} strs
     * @return {string[][]}
     */
    var groupAnagrams = function (strs) {
      const map = new Map()
    
      for (let str of strs) {
        const key = str.split('').sort().join()
        map.set(key, map.has(key) ? [...map.get(key), str] : [str])
      }
    
      return [...map.values()]
    }
    // @lc code=end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22