File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * 조건
3+ * 문자열은 영어 소문자
4+ * 서로 anagram이 되는 쌍을 배열로 묶어서 리턴
5+ * 자기 자신은 anagram 혼자서 가능함
6+ * return 하는 배열 순서는 관계없음
7+
8+ * 아이디어
9+ * strs를 돌면서 str에 어떤 알파벳이 몇개씩 있는지를 계산한다
10+ * 알파벳 개수가 같은 문자열끼리 몹는다
11+ */
12+ function groupAnagrams ( strs : string [ ] ) : string [ ] [ ] {
13+ const anagramMap = new Map < string , string [ ] > ( ) ;
14+
15+ for ( const str of strs ) {
16+ const sortedStr = generateAnagramKey2 ( str ) ;
17+ if ( ! anagramMap . has ( sortedStr ) ) {
18+ anagramMap . set ( sortedStr , [ ] ) ;
19+ }
20+
21+ anagramMap . get ( sortedStr ) ! . push ( str ) ;
22+ }
23+
24+ return Array . from ( anagramMap . values ( ) ) ;
25+ }
26+ // TC: O(N * M)
27+ // SC: O(N * M)
28+
29+ function generateAnagramKey1 ( str : string ) : string {
30+ return str . split ( "" ) . sort ( ) . join ( "" ) ;
31+ }
32+ // TC: O(NlogN)
33+ // SC: O(N)
34+
35+ function generateAnagramKey2 ( str : string ) : string {
36+ let count = new Array ( 26 ) . fill ( 0 ) ;
37+
38+ for ( let c of str ) {
39+ count [ c . charCodeAt ( 0 ) - "a" . charCodeAt ( 0 ) ] ++ ;
40+ }
41+
42+ return count . join ( "-" ) ;
43+ }
44+ // TC: O(N)
45+ // SC: O(1)
You can’t perform that action at this time.
0 commit comments