File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ /**
3+ * ๊ฐ ๋ฌธ์์ด์ ์ํ๋ฒณ ๋ฑ์ฅ ํ์๋ฅผ ํค๋ก ์ฌ์ฉํด
4+ * ๊ฐ์ ์ ๋๊ทธ๋จ๋ผ๋ฆฌ ๊ทธ๋ฃนํํ๋ค.
5+ *
6+ * ์๊ฐ ๋ณต์ก๋: O(S)
7+ * ๊ณต๊ฐ ๋ณต์ก๋: O(n)
8+ *
9+ * S: ๋ชจ๋ ๋ฌธ์์ด ๊ธธ์ด์ ํฉ
10+ * n: ๋ฌธ์์ด์ ๊ฐ์
11+ */
12+ public List <List <String >> groupAnagrams (String [] strs ) {
13+ Map <String , List <String >> groups = new HashMap <>();
14+
15+ for (String word : strs ) {
16+ int [] frequency = new int [26 ];
17+
18+ // ์ํ๋ฒณ๋ณ ๋ฑ์ฅ ํ์๋ฅผ ๊ณ์ฐํ๋ค.
19+ for (int i = 0 ; i < word .length (); i ++) {
20+ frequency [word .charAt (i ) - 'a' ]++;
21+ }
22+
23+ // ๋น๋ ๋ฐฐ์ด์ ๊ฐ์ ๋ด์ฉ๋ผ๋ฆฌ ๋น๊ตํ ์ ์๋ ํค๋ก ๋ณํํ๋ค.
24+ String key = Arrays .toString (frequency );
25+
26+ // ๊ฐ์ ํค๋ฅผ ๊ฐ์ง ๋ฌธ์์ด์ ๋์ผํ ๊ทธ๋ฃน์ ์ถ๊ฐํ๋ค.
27+ groups .computeIfAbsent (key , ignored -> new ArrayList <>())
28+ .add (word );
29+ }
30+
31+ return new ArrayList <>(groups .values ());
32+ }
33+ }
You canโt perform that action at this time.
0 commit comments