
์... ์ฒ์ ํ์ด๋ณด๋ Medium๋ฌธ์ ...
Hash Map์ ์ฌ์ฉํ๋ ๊ฑด ์ง์์ ํ์์ง๋ง, ๋๋ฌด์ง ํ ๋ฐฉ๋ฒ์ ๋ชฐ๋ผ์ 30๋ถ ๊ณ ๋ฏผํ๊ณ ํ์ด๋ฅผ ์ฐพ์๋ณด์๋ค
ํ์ด ์ถ์ฒ: https://www.youtube.com/watch?v=vzdNOK2oB2E&ab_channel=NeetCode
ํน์ ์ดํดํ๊ฒ ํ๋ฆฐ ์ ์์ผ๋ ์ง์ ํด์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค.
์๊ฐ ๋ฐฉ์
a๋ถํฐ z๋ 26๊ฐ์ character์ด๊ณ , ํ ๋จ์ด์ ์ด character๋ค์ด ์ผ๋ง๋ ๋์ค๋์ง ์ฒดํฌ๋ฅผ ํ๋ค
๊ทธ๋ฆฌ๊ณ ๊ฐ์ anagram๋ผ๋ฆฌ ๋ฌถ์ด์ ์ถ๋ ฅ์ ํด์ฃผ๋ฉด ๋๋ค.
์ดํดํ๊ธฐ ์ด๋ ค์ ๋ ์ ๋ค
์ผ๋จ Hash Map์ ๊ตฌ์ฑ๋ถํฐ ์ ๋ฅผ ๋ง์ด ๋จน์๋ค

ํ์ด๋ฅผ ๋ณด๋ฉด์ ์์ดํจ๋๋ก ๋ ธํธ๋ฅผ ๋จ๊ฒผ๋๋ฐ ๋๋ฌด์ง ์ key์ ๋ญ๊ฐ ๋ค์ด๊ฐ๋์ง ์ดํด๊ฐ ์ ๋๋ค...
๊ทธ๋์ GPT๋ฅผ ๋๋ ค์ ์ด๋ป๊ฒ ๊ตฌ์ฑ๋๊ฑด์ง ์ฐพ์๋ดค๋ค
{(1, 0, 0, ..., 0): ['bat'], (1, 1, 1, ..., 0): ['eat', 'tea', 'ate'], (1, 0, 1, ..., 1): ['tan', 'nat']}
์ด๋ฐ ์์ผ๋ก ์ด string์ ๊ฐ character๊ฐ ๋ช ๋ฒ์ด ๋ค์ด๊ฐ๋์ง๋ฅผ ๋ํ๋ธ tuple์ด key๊ฐ ๋๋ ๊ฑฐ์๋ค...
defaultdict(list)๋ ์ฐ๋ฆฌ์ ๋์ ๋๋ฆฌ์ ๊ฐ์ ๋ฆฌ์คํธ๋ก ์ง์ ํด์ค๋ค๋ ๊ฒ์ผ๋ก ์ดํดํ๋ค
์ฐธ๊ณ : ์์ ์ฐธ๊ณ ํ ์ ํ๋ธ ๋ฐ์ ๋๊ธ๊ณผ https://www.geeksforgeeks.org/defaultdict-in-python/
๊ทธ๋ฆฌ๊ณ ord()๋ ๋ถ๋ช ํ ํ๊ต์์ ๋ฐฐ์ด ๋ด์ฉ์ธ๋ฐ ๊ธฐ์ต์ด ๊ฐ๋ฌผ๊ฐ๋ฌผํ๋ค
๊ทธ๋์ ์ฐพ์๋ณด๋ ord()๋ number representing the unicode code of a specified character ์๋ค
์) ord("a")๋ 97 ord("z")๋ 122์ด๋ค
๊ทธ๋์ count[ord(c) - ord("a")] += 1 ๋ a๋ถํฐ z๊ฐ ๋์ค๋ ํ์๋ฅผ ์ง์ ํด์ค๋ค๊ณ ์ดํดํ๋ค
๊ทธ๋ฆฌ๊ณ res[tuple(count)].append(s)
โญ๏ธ ๊ธฐ์ตํ์: list๋ key๊ฐ ๋ ์ ์๋ค
์์ ์ค๋ช ํ๋ ๊ฒ์ฒ๋ผ, ์ฐ๋ฆฌ์ key๋ ํํ์ด๋ค. ๊ทธ๋์ count๋ฅผ ํํ๋ก ๋ณํํด ์ฃผ๊ณ ๊ฑฐ๊ธฐ์ ์ฐ๋ฆฌ์ ๊ฐ์ธ s๋ฅผ ๋ฃ๋ ๋ฐฉ์์ด๋ค
๋ง์ง๋ง์ผ๋ก value๋ง ๋ฆฌํดํ๋ฉด ๋๋๊น, values()๋ก ๋ฆฌํด์ ๋ฐ์ผ๋ฉด ๋๋ค
๐ป ์ฝ๋
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list) # define a dictionary with values as a list
for s in strs:
count = [0] * 26 # a-z 26๊ฐ์ character๋ก ๋์ด์์ผ๋๊น
for c in s:
count[ord(c) - ord("a")] += 1 #increment the count of frequency of each character in the string.
res[tuple(count)].append(s) # in Python, list cannot be keys, tuples are non mutable
return res.values()
๋ด ๊ฒ์ผ๋ก ๋ง๋๋ ๋ฐ์ ํ์ํ ์๊ฐ์ด ์ ๋ง ๋ง์ด ์์๋๋ค (์๋ง 1์๊ฐ 30๋ถ์ ๊ฑธ๋ฆฐ๋ฏ...)
๋ฉฐ์น ๋ค์ ๋ ๋ค์ ํ์ด๋ด์ผ๊ฒ ๋ค...
'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 746. Min Cost Climbing Stairs (Easy) [Python] (0) | 2024.02.04 |
|---|---|
| 70. Climbing Stairs (Easy) [Python] (2) | 2024.02.03 |
| 1. Two Sum (Easy) [Python] (0) | 2024.02.03 |
| 242. Valid Anagram (Easy) [Python] (0) | 2024.02.03 |
| 217. Contains Duplicate (Easy) [Python] (0) | 2024.02.03 |