[string] 49. Group Anagrams

younoah·2021년 12월 30일
0

[leetcode]

목록 보기
8/12

문제

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.

문자열 스트의 배열이 주어지면, 아나그램을 함께 그룹화합니다. 답변은 어떤 순서로든 반환할 수 있습니다.

애너그램(Anagram)은 다른 단어나 구의 글자를 재배치하여 만든 단어나 구문으로, 일반적으로 모든 원래 글자를 정확히 한 번 사용합니다.

예시

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

제약

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

코드

const groupAnagrams = (strs) => {
    const anagram = {}
    
    strs.forEach(str => {
        const sortedStr = str.split('').sort().join('') 
        
        if (anagram.hasOwnProperty(sortedStr)) {
            anagram[sortedStr].push(str);
        } else {
            anagram[sortedStr] = [str];
        }
    })
    
    return Object.values(anagram)
};

풀이

  • 애너그램을 사전형태로 담기위해 anagram 이라는 객체 변수를 선언한다.
  • 입력받은 strs 를 순회하며 각 str 을 정렬하여 애너그램의 키로 사용한다.
  • 만약 정렬된 stranagram의 키로 존재하면 해당 키의 value에 push하고 존재하지 않는다면 배열형태로 정의해준다.
  • 최종적으로 anagram 객체의 밸류들만 뽑아서 리턴한다.
profile
console.log(noah(🍕 , 🍺)); // true

0개의 댓글