File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ anagram์ sortํ๋ฉด ๋์ผํ๋ค๋ ์ฑ์ง์ ์ด์ฉํด์
3
+ sorted str์ key๋ก ๋ฌธ์์ด str๋ฐฐ์ด์ value๋ก ๊ฐ์ง๋ ๋์
๋๋ฆฌ๋ฅผ ๋ง๋ ๋ค
4
+ ans์ ์ปดํ๋ฆฌํจ์
์ ์ด์ฉํด ๋์
๋๋ฆฌ์ value๋ฅผ ๋ฐฐ์ด์ ๋ฃ์ด ๋ง๋ ๋ค
5
+
6
+ TC : O(WlogW * N)
7
+ strs์ ํ๊ท ๋ฌธ์์ด๊ธธ์ด W, strs์ ๊ฐ์๋ฅผ N์ด๋ผ๊ณ ํ ๋
8
+ sort์ ์๊ฐ๋ณต์ก๋ => WlogW
9
+ for๋ฌธ => N
10
+
11
+ SC : O(W * N)
12
+ anagrams๊ฐ ์ฐจ์งํ๋ ๊ณต๊ฐ์ ๋ฌธ์์ด์ ๊ธธ์ด์ ๊ฐ์์ ๋น๋กํ๋ค
13
+
14
+
15
+ - defaultdict ๋ง๋ค ๋ ์ธ์๋ก ๋น๋ฐฐ์ด([])์ด ์๋ ํ์
(list)์ ๋ฃ์ด์ค์ผํ๋ค
16
+
17
+ - ์๊ณ ๋ฌ๋ ์ ๋ค๋ฅธํ์ด๋ก ๋ฌธ์์ด์ ๋์ค๋ ์ํ๋ฒณ ๋น๋ ์(count = [0] * 26)๋ก anagram์ ํ๋ณํ๋ ๋ฒ๋ ์๋ค
18
+ ๋์
๋๋ฆฌ์ key๋ ๋ถ๋ณํด์ผ ํ๊ธฐ ๋๋ฌธ์ count๋ฅผ ํํ๋ก ๋ฐ๊พธ๋ ๊ฒ ์ฃผ์
19
+
20
+ """
21
+
22
+ from collections import defaultdict
23
+
24
+ class Solution :
25
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
26
+ anagrams = defaultdict (list )
27
+ for s in strs :
28
+ sorted_s = "" .join (sorted (s ))
29
+ if sorted_s in anagrams :
30
+ anagrams [sorted_s ].append (s )
31
+ else :
32
+ anagrams [sorted_s ] = [s ]
33
+ ans = [value for value in anagrams .values ()]
34
+ return ans
You canโt perform that action at this time.
0 commit comments