[LeetCode] 49. Group Anagrams

#49. Group Anagrams

문제

단어의 배열을 받아서, 단어를 구성하는 알파벳의 순서가 다르더라고 같은 알파벳 들로 구성된 단어들을 묶어서 배열로 반환하는 문제입니다.

EX) ’eat’, ‘ate’, ’tea’는 같이 묶여서 반환 됩니다.

설명

우선, 단어에 문자 순서가 다른 모든 단어를 찾고 저장하기 위해서 기준으로 알파벳 순으로 정렬된 단어를 만든다. 예를 들어 eat, ate, tae에서는 알파벳 순서로 aet가 키가 되는 것이다. 이 키를 만들기 위해서 split()으로 단어를 쪼개고, sort() 를 사용해서 알파벳의 순서를 정렬하고, join() 을 이용해서 배열을 다시 단어로 만듭니다. 이 키를 가지고 data라는 json을 만들고 모든 단어를 돌면서 값을 추가한다. 그리고 추가된 값을 반환 형식에 맞춰서 반환해준다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var groupAnagrams = function(strs) {
  const data = {}; // 단어를 키로, anagram 단어들을 값으로 가진다.
  const result = []; // 리턴할 결과를 저장하는 배열
  for(let str of strs) { // 주어진 단어 배열을 반복문으로 돌린다.
    const word = str.split('').sort().join(''); // 주어진 단어를 쪼개고 정렬하고 합쳐서 key가 될 값으로 만든다.
    if (!data[word]) data[word] = []; // data에 없다면 초기화를 해주고,
    data[word].push(str); // 추가한다.
  }
  for(let key in data) {
    result.push(data[key]); // 반환할 값을 만든다.
  }
  return result;
};

LeetCode

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:

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

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lower-case English letters.
Built with Hugo
Theme Stack designed by Jimmy