File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * TC: O(N * S)
3+ * SC: O(N)
4+ * N: strs.length, S: strs[i].length
5+ *
6+ * ํ์ด
7+ * ์ฃผ์ด์ง ๋ฐฐ์ด strs์ ๊ฐ ์์์ ํค๋ฅผ ๊ตฌํด์ ๊ฐ์ ์์๋ผ๋ฆฌ ๋ฌถ์ด ์ ๋ต์ ์ฐพ๋๋ค.
8+ * ํค ๊ตฌํ๋ ๋ฐฉ๋ฒ์ ์ฃผ์ด์ง ๋ฌธ์์ด์ ์ฌ์ฉ๋ ์ํ๋ฒณ ๊ฐฏ์์ด๋ค.
9+ */
10+
11+ /**
12+ * @param {string[] } strs
13+ * @return {string[][] }
14+ */
15+ var groupAnagrams = function ( strs ) {
16+ // 1. ํค๋ฅผ ์ ์ฅํ Map
17+ const keyMap = new Map ( ) ;
18+
19+ for ( const str of strs ) {
20+ // 2. ํค๋ฅผ ๊ตฌํด์ ๋์ผํ ํค๋ฉด ๊ฐ์ ๊ฐ(๋ฐฐ์ด)์ ์ถ๊ฐํ๋ค.
21+ const key = generateKey ( str ) ;
22+
23+ if ( keyMap . has ( key ) ) {
24+ keyMap . get ( key ) . push ( str ) ;
25+ } else {
26+ keyMap . set ( key , [ str ] ) ;
27+ }
28+ }
29+
30+ // 3. ํค๋ฅผ ์ ์ฅํ Map์ ๊ฐ๋ค์ ๋ชจ์ ์ ๋ต์ ๋ฐํํ๋ค.
31+ const result = [ ] ;
32+
33+ for ( const v of keyMap . values ( ) ) {
34+ result . push ( v ) ;
35+ }
36+
37+ return result ;
38+
39+ // ํค ๊ตฌํ๋ ํจ์
40+ function generateKey ( str ) {
41+ // ๊ฐ ์ํ๋ฒณ์ด ๋ช๊ฐ ๋ฑ์ฅํ๋์ง ๊ธฐ๋กํ ๋ฐฐ์ด
42+ const usedCount = new Array ( 26 ) . fill ( 0 ) ;
43+
44+ for ( const s of str ) {
45+ // ์์คํค์ฝ๋๋ก ๋ณํํ์ฌ index๋ฅผ ๊ตฌํ๋ค.
46+ usedCount [ s . charCodeAt ( ) - 97 ] += 1 ;
47+ }
48+
49+ return usedCount . join ( "," ) ;
50+ }
51+ } ;
You canโt perform that action at this time.
0 commit comments