欣迪

出處: https://leetcode.com/problems/group-anagrams/

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

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

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

解法

/**
 * @param {string[]} strs
 * @return {string[][]}
 */

var groupAnagrams = function(strs) {
  	// 排除只有一個字的狀態
    if (strs.length === 1) return [strs]
  	// 創立一個 Map 記錄易位構詞得組合
    const strMap = new Map()
    for (let i = 0; i < strs.length; i++) {
      	// 設定 Map 的 key ,把文字拆散,並按照字母順序排列重組
        const key = strs[i].split('').sort().join('')
        // 取得 Map 裡面已經有的 value , 如果沒有給一個空的 array
        const value = strMap.get(key) || []
        // 把新的值加上去 Map 裡面
        value.push(strs[i])
        strMap.set(key, value)
    }
  	// 把 Map 變成陣列,並格式為我們要的內容
    return [...strMap].map(item => item[1])
};

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。