์• ์ •์ฝ”๋”ฉ ๐Ÿ’ป

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