File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Runtime: 24ms, Memory: 55.95MB
3
+ *
4
+ * 접근: 문자들끼리 anagram 관계인 경우, 정렬했을 때 같은 값을 가지기에 각 문자열 정렬 후 비교.
5
+ */
6
+
7
+ function isAnagram ( s : string , t : string ) : boolean {
8
+ if ( s . length !== t . length ) {
9
+ return false ;
10
+ }
11
+ return sortedString ( s ) === sortedString ( t ) ;
12
+ }
13
+
14
+ function sortedString ( s : string ) : string {
15
+ return s . split ( "" ) . sort ( ) . join ( "" ) ;
16
+ }
17
+
18
+ /**
19
+ * Runtime: 29ms, Memory: 55.02MB
20
+ *
21
+ * 접근: 문자들끼리 anagram 관계인 경우, 각 문자들의 count가 동일할 것이기에 Map 자료구조를 이용해서 합/차 계산
22
+ * Time Complexity: O(N)
23
+ * Space Complexity: O(N)
24
+ */
25
+ function isAnagram ( s : string , t : string ) : boolean {
26
+ if ( s . length !== t . length ) {
27
+ return false ;
28
+ }
29
+
30
+ let map = new Map < string , number > ( ) ;
31
+ for ( const char of s ) {
32
+ if ( map . has ( char ) ) {
33
+ map . set ( char , map . get ( char ) ! + 1 ) ;
34
+ } else {
35
+ map . set ( char , 1 ) ;
36
+ }
37
+ }
38
+
39
+ for ( const char of t ) {
40
+ if ( map . has ( char ) ) {
41
+ map . set ( char , map . get ( char ) ! - 1 ) ;
42
+ } else {
43
+ return false ;
44
+ }
45
+ }
46
+
47
+ for ( const value of map . values ( ) ) {
48
+ if ( value !== 0 ) {
49
+ return false ;
50
+ }
51
+ }
52
+
53
+ return true ;
54
+ }
55
+
56
+ console . log ( isAnagram ( "anagram" , "nagaram" ) ) ;
You can’t perform that action at this time.
0 commit comments