https://leetcode.com/problems/group-anagrams/
Group Anagrams - LeetCode
Can you solve this real interview question? Group Anagrams - 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
leetcode.com
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.
๋ด๊ฐ ํผ ๊ฒ:
๋ฆฌ์คํธ๋ก ์ ๋ฒ์ ๋์จ count ์ฐ๋ ค๋ค๊ฐ ํฌ๊ธฐํ๊ณ sorted ์ผ๋ค...^^
๋๋ฌด ํธ๋ฆฌํ๊ฑธ? ๊ทธ๋ฆฌ๊ณ ๋์ ๋๋ฆฌ ์ฌ์ฉ ํด๋ดค๋๋ฐ key, value๋ก ๋์ด์์ด์ for๋ฌธ ๋๋ฉด์ soted ๋ key ์๋ค๊ฐ ํด๋นํ๋ word๋ฅผ ๋ฃ์ด์ฃผ๋ ๋ฐฉ์์ผ๋ก ํ๋ค. ๋์ ๋๋ฆฌ ์ฌ์ฉ๋ฒ์ด ์ต์ํ์ง ๋ชปํด์ ๋ง์ด ํค๋งธ๋ค.
class Solution(object):
def groupAnagrams(self, strs):
result ={}
for word in strs:
sortedWord = ''.join(sorted(word))
if sortedWord in result:
result[sortedWord].append(word)
else:
result[sortedWord] = [word]
return result.values()
๋ค๋ฅธ ์ฌ๋์ด ํผ ๊ฒ ๋ช ๊ฐ ์ฐพ์๋ดค๋๋ฐ ๋น์ทํ๋ค.
sorted(word)๋ฅผ ํ๋ฉด list๊ฐ ๋์ค๋๋ฐ ex. ['a', 'b', 'c'] ๋ฆฌ์คํธ์ ๋ด๊ธด ๋ฌธ์์ด์ ์ฐ๊ฒฐํ ๋. join์ ์ฌ์ฉํ๋ค. ์ด๋ ์ค๊ฐ์ ๋ฃ์ด์ค ๋ฌธ์๋ ์ฌ์ฉํ ์ ์๋ค.
๋๋ ๊ณต๋ฐฑ์ผ๋ก ์ฌ์ฉ ํ๋๋ฐ ', '.join(sorted(word)) ์ด๋ ๊ฒ ์ฌ์ฉํ๋ฉด "a, b, c" ์ด๋ฐ ์์ผ๋ก ๋ฐํ ๋๋ฌด ํธ๋ฆฌํ๋ค
.append(word) ๋ ๋ฆฌ์คํธ์ ๊ฐ ์ถ๊ฐ.
= [word] ๋ ๋ฆฌ์คํธ ์์ฑ.
'์๊ณ ๋ฆฌ์ฆ > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
347. Top K Frequent Elements (0) | 2023.08.20 |
---|---|
1. Two Sum (0) | 2023.08.16 |
242. Valid Anagram (0) | 2023.08.13 |
217. Contains Duplicate (0) | 2023.08.10 |