๐Ÿค” ๋ฌธ์ œ


 

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

๐Ÿ˜€ ํ’€์ด


์œ„ ๋ฌธ์ œ๋Š” ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด ๋ฐฐ์—ด๋“ค์„ anagram ๋ผ๋ฆฌ ๋ชจ์•„๋ณด๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

 

๋ฌธ์ œ ํ’€์ด์—์„œ ํ•ต์‹ฌ์ด ๋œ ์•„์ด๋””์–ด๋Š” "anagram์ด๋ผ๋ฉด ๋ฌธ์ž์—ด์„ ์ •๋ ฌํ–ˆ์„ ๊ฒฝ์šฐ ๊ฐ™์€ ๊ฐ’์ด ๋‚˜์˜จ๋‹ค" ์ž…๋‹ˆ๋‹ค.

 

๋”ฐ๋ผ์„œ ํ’€์ด๋ฅผ ์ง„ํ–‰ํ•œ ํ๋ฆ„์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

  1. ๋ฌธ์ž์—ด ๋ฐฐ์—ด์„ ํ•˜๋‚˜์”ฉ ์‚ดํŽด๋ณด๋Š” ๊ณผ์ •์—์„œ ๊ฐ ๋ฌธ์ž์—ด์„ ์ •๋ ฌํ•ด๋ณธ๋‹ค.
  2. ์ •๋ ฌํ•œ ๋’ค dict์— ๋ฌธ์ž์—ด์„ ๋„ฃ๋Š”๋‹ค.
  3. ์ด ๋•Œ key๋Š” ์ •๋ ฌ๋œ ๋ฌธ์ž์—ด, value๋Š” ์›๋ž˜ ๋ฌธ์ž์—ด์ด๋‹ค. ( value๋Š” ๋ฐฐ์—ด์— ์ €์žฅ๋จ )
  4. ๋ฌธ์ž์—ด ๋ฐฐ์—ด์„ ๋‹ค ์‚ดํŽด๋ณด์•˜๋‹ค๋ฉด dict์˜ values๋“ค์ด ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•˜๋Š” ์ •๋‹ต์ด ๋ฉ๋‹ˆ๋‹ค.

์ด ๋•Œ 2 ~ 3๋ฒˆ ๊ณผ์ •์„ ๊ฐ„๋‹จํžˆ ํ•˜๊ธฐ์œ„ํ•ด ํŒŒ์ด์ฌ์—์„œ ์ œ๊ณตํ•˜๋Š” defaultdict๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•ฉ๋‹ˆ๋‹ค.


๐Ÿ’ป ํ’€์ด ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = defaultdict(list)

        for str in strs:
            sorted_str = ''.join(sorted(str))
            anagrams[sorted_str].append(str)

        return anagrams.values()

 

๋ฐ˜์‘ํ˜•

'Algorithm > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] 33. Search in Rotated Sorted Array - Python  (0) 2022.05.05
[LeetCode] 42. Trapping Rain Water - Python  (0) 2022.04.27
๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค!