← 모든 글
개발

[Leetcode] Group Anagrams

아직 한국어 번역이 없습니다. 영문 원문을 표시합니다.

49. Group Anagrams

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

Example 1:

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

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

Explanation:

There is no string in strs that can be rearranged to form "bat".

The strings "nat"and "tan"are anagrams as they can be rearranged to form each other.

The strings "ate", "eat", and "tea"are anagrams as they can be rearranged to form each other.

Example 2:

Input: strs = [""]

Output: [[""]]

Example 3:

Input: strs = ["a"]

Output: [["a"]]

Constraints:

1 <= strs.length <= 10``4

0 <= strs[i].length <= 100

strs[i] consists of lowercase English letters.

how to approach?

function groupAnagrams(strs: string[]): string[][] {

    let map = new Map<string,string[]>()

    for(let item of strs){
        const key = item.split('').sort().join()
        if(!map.get(key)) map.set(key,[])
        map.get(key).push(item)
    }
    return Array.from(map.values())
}
  1. create a new Map to set key and value, key will be string and value will string array.
  2. check the strs's each item and split them into one by one and sort it out and join them.
  3. it will be the key of the Map and the value will be the item's original value, it will be saved in the array, if there is no item in the array yet then it will set the [] as value.
  4. after the for loop, the return will be the array from Map's value which has the grouped string as the anagram key.

summary

this leetcode is solved by typescript language.

Using map to check the each item's key value in the sorted string, and set the item itself in the value of array and lastly return the array from Map.values.