File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 문제 유형
3+ * - String
4+ *
5+ * 문제 설명
6+ * - 두 문자열이 애너그램인지 확인하기
7+ *
8+ * 아이디어
9+ * 1) 문자열을 맵으로 변환하고, 정렬 후 비교하기
10+ * 2) 문자열 정렬 없이 하나의 map으로 더하고 빼기하여 0인지 확인하기
11+ */
12+ function mapString ( str : string ) {
13+ const map = new Map < string , number > ( ) ;
14+ for ( let i = 0 ; i < str . length ; i ++ ) {
15+ map . set ( str [ i ] , ( map . get ( str [ i ] ) || 0 ) + 1 ) ;
16+ }
17+ return map ;
18+ }
19+ function isAnagram ( s : string , t : string ) : boolean {
20+ const sMap = mapString ( s ) ;
21+ const tMap = mapString ( t ) ;
22+
23+ const sKeys = [ ...sMap . keys ( ) ] . sort ( ) . join ( "" ) ;
24+ const tKeys = [ ...tMap . keys ( ) ] . sort ( ) . join ( "" ) ;
25+
26+ if ( sKeys !== tKeys ) return false ;
27+
28+ for ( let i = 0 ; i < sKeys . length ; i ++ ) {
29+ const key = sKeys [ i ] ;
30+ if ( sMap . get ( key ) !== tMap . get ( key ) ) return false ;
31+ }
32+
33+ return true ;
34+ }
35+
36+ // 아이디어 2
37+ function isAnagramDeveloped ( s : string , t : string ) : boolean {
38+ if ( s . length !== t . length ) return false ;
39+
40+ const count = new Map < string , number > ( ) ;
41+
42+ for ( let i = 0 ; i < s . length ; i ++ ) {
43+ count . set ( s [ i ] , ( count . get ( s [ i ] ) || 0 ) + 1 ) ;
44+ count . set ( t [ i ] , ( count . get ( t [ i ] ) || 0 ) - 1 ) ;
45+ }
46+
47+ for ( const val of count . values ( ) ) {
48+ if ( val !== 0 ) return false ;
49+ }
50+
51+ return true ;
52+ }
You can’t perform that action at this time.
0 commit comments