๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 49 - Group Anagrams (Medium)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 49๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ์ž…๋ ฅ์—์„œ Anagram์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

Anagram์€ ์ˆœ์„œ์— ์ƒ๊ด€์—†์ด ๋‘ ๋‹จ์–ด๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๋ฌธ์ž์˜ ์ข…๋ฅ˜์™€ ๊ฐœ์ˆ˜๊ฐ€ ๋™์ผํ•œ ๊ด€๊ณ„๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค.
Anagram์„ ํŒ๋‹จํ•˜๋Š” ์ง๊ด€์ ์ธ ๋ฐฉ๋ฒ•์€ ๋‘ ๋‹จ์–ด๋ฅผ ์ •๋ ฌํ•œ ๋’ค ๊ฐ™์€ ์ง€ ๋น„๊ตํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

Javascript ์—์„œ String ์„ ์ •๋ ฌํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” spread ์—ฐ์‚ฐ์„ ํ†ตํ•ด Array๋กœ ๋ฐ”๊ฟ”์ค€ ์ดํ›„ sort ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

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

var groupAnagrams = function (strs) {
  const anagram = new Map();

  for (let word of strs) {
    let sorted = [...word].sort().join("");

    // ํ˜„์žฌ ์กด์žฌํ•˜๋Š” anagram ์ธ์ง€ ์กฐ์‚ฌ
    if (anagram.has(sorted)) {
      anagram.get(sorted).push(word);
    } else {
      anagram.set(sorted, [word]);
    }
  }

  const answer = Array.from(anagram.values());
  return answer;
};

const input = ["eat", "tea", "tan", "ate", "nat", "bat"];
console.log(groupAnagrams(input));
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 678 - Valid Parenthesis String (Medium)  (0) 2021.03.02
LeetCode 1094 - Car Pooling (Medium)  (0) 2021.03.02
LeetCode 200 - Number of Islands (Medium)  (0) 2021.03.02
LeetCode 64 - Minimum Path Sum (Medium)  (0) 2021.03.02
LeetCode 55 - Jump Game (Medium)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€