๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

[Leetcode] Group Anagrams

 

 

ํ•ด์„ค ์ฝ”๋“œ 

 

class Solution(object): 
    def groupAnagrams(self, strs):
        d = {}
        for str in strs:
            key = ''.join(sorted(str))
            if key not in d:
                d[key] = [str]
            else:
                d[key].append(str)
        return d.values()
๋ถ„์„ > ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ํ’€๋ ค๊ณ  ํ–ˆ์ง€๋งŒ, value๊ฐ’์— ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ถ”๊ฐ€๊ฐ€ ์•ˆ๋˜์–ด์„œ ๊ณ„์† ํ’€์ง€ ๋ชปํ–ˆ๋‹ค. ์• ๋„ˆ๊ทธ๋žจ ๊ด€๊ณ„์— ์žˆ๋Š” ๋‹จ์–ด๋“ค์€ ์ •๋ ฌํ–ˆ์„ ๋•Œ ๊ฐ™๋‹ค๋Š” ๊ฒƒ์„ ์ด์šฉํ•˜์—ฌ ํ•ด์‹œ๋งต์˜ key๊ฐ’์—๋Š” ์ด๋“ค์„ ์ •๋ ฌํ•˜์—ฌ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“  ๊ฒƒ์„ ๋„ฃ๊ณ , value๊ฐ’์—๋Š” ๊ฐ™์€ key๋ฅผ ๊ฐ€์ง„ ๋‹จ์–ด๋“ค์„ ๋ฐฐ์—ด๋กœ appendํ•˜๋ฉด ๋‚ด๊ฐ€ ์›ํ•˜๋Š” ํ•ด์‹œ๋งต์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์—ˆ๋‹ค. 

 

 

 

 

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