본문 바로가기
LeetCode

49. Group Anagrams

by 초코맛젤리 2022. 11. 26.

 

49. Group Anagrams

Medium


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"]]

 

Constraints:

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

이 문제는 주어진 strs의 단어들의 애너그램 별 그룹으로 묶는 문제이다.

애너그램이란..?

단어나 문장을 구성하고 있는 문자의 순서를 바꾸어 다른 단어나 문장을 만드는 것이다. (각 단어는 한번만 사용)

 

간단하게 map을 이용해서 풀 수 있는 문제이다.

주어진 단어들을 정렬한뒤

그것을 키로 사용하여 동일한 키를 가지는 것 끼리 묶어주면 된다.

var groupAnagrams = function(strs) {
    const map = new Map()
    
    strs.forEach(str=>{
        const key = str.split('').sort().join('') 
        if(!map.has(key)) map.set(key,[])
        map.get(key).push(str)
    })
    
    const ans = [] 
    for(const values of map.values()){
        ans.push(values)
    }
    
    return ans
};

'LeetCode' 카테고리의 다른 글

2225. Find Players With Zero or One Losses  (0) 2022.11.28
967. Numbers With Same Consecutive Differences  (0) 2022.11.26
216. Combination Sum III  (0) 2022.11.24
39. Combination Sum  (0) 2022.11.24
LeetCode - Weekly Contest 296 풀이 및 후기  (0) 2022.06.05