๐What I thought
- ์์๋ ๋ค๋ฅด์ง๋ง ๋ฌธ์ ๊ตฌ์ฑ์ด ๊ฐ์ ๋จ์ด๋ค์ ์ฐพ์์ผ ํด โ ๊ฐ๋ค๋ ๊ฑธ ์ด๋ป๊ฒ ์์ง?
โ ๋จ์ด๋ฅผ ์ ๋ ฌํด๋ณด์
- ๊ทธ๋ฆฌ๊ณ ์ด ๋จ์ด๋ค์ ๋ฌถ์ด์ผ ํด
โ ๋์
๋๋ฆฌ๋ฅผ ํ๋ ๋๊ณ ์ ๋ ฌ๋ ๋จ์ด๋ฅผ key, ๊ทธ๋ฆฌ๊ณ ํด๋น ๋จ์ด๋ฅผ value์ ๋ฃ์ด์ฃผ์
{sorted_word: \[word1, word2, ...]}
๐ํ์ด
๐Sort & Dictionary
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hs = dict()
for word in strs:
key = "".join(sorted(word))
if hs.get(key, 0):
hs[key].append(word)
else:
hs[key] = [word]
return list(hs.values())
๐What I learned
- Dictionary์ key์๋ immutable ๊ฐ์ฒด๋ง ๋ค์ด์ฌ ์ ์์ โ list๋ ๋ถ๊ฐ (๊ทธ๋์ string์ผ๋ก ๋ฐ๊ฟ์ฃผ์์)
sorted()๋ฅผ ์จ์ ์ ๋ ฌํ๋ฉด list ํํ๋ก ์ ๋ ฌ๋ ๋ฐ์ดํฐ๋ฅผ return (a.sort()๋ ๋ฐํ๊ฐ ์์)
๐๊ด๋ จ ์ง์