1
+ /**
2
+ * @param {string } s
3
+ * @param {string } t
4
+ * @return {boolean }
5
+ */
6
+ var isAnagram = function ( s , t ) {
7
+ const mapS = new Map ( ) ;
8
+ const mapT = new Map ( ) ;
9
+
10
+ [ ...s ] . map ( ( item ) => {
11
+ if ( mapS . has ( item ) ) {
12
+ const itemCount = mapS . get ( item ) ;
13
+ mapS . set ( item , itemCount + 1 ) ;
14
+ } else {
15
+ mapS . set ( item , 1 ) ;
16
+ }
17
+ } ) ;
18
+
19
+ [ ...t ] . map ( ( item ) => {
20
+ if ( mapT . has ( item ) ) {
21
+ const itemCount = mapT . get ( item ) ;
22
+ mapT . set ( item , itemCount + 1 ) ;
23
+ } else {
24
+ mapT . set ( item , 1 ) ;
25
+ }
26
+ } ) ;
27
+
28
+ // NOTE - t๊ฐ s์ anagram์ด๋ผ๋ ๋ป์ ๊ฐฏ์๊ฐ ๊ฐ์ง์์๋ ๋๋ค๊ณ ์ดํดํ์ผ๋ anagram์ ์๋ s๊ตฌ์ฑ์์ ๋ชจ์๋,๋จ๊น์์ด t๋ฅผ๋ง๋ค ์ ์๋ ์ํ
29
+ if ( mapS . size !== mapT . size ) {
30
+ return false ;
31
+ }
32
+
33
+ for ( const [ key , value ] of mapS ) {
34
+ if ( mapT . get ( key ) !== value ) {
35
+ return false ;
36
+ }
37
+ }
38
+
39
+ return true ;
40
+ } ;
41
+
42
+ // ์๊ฐ๋ณต์ก๋: O(n)
43
+ // - ๋ฌธ์์ด s์ t๋ฅผ ๊ฐ๊ฐ ํ ๋ฒ์ฉ ์ํ: O(n) + O(n) = O(2n) = O(n)
44
+ // - Map ๋น๊ต๋ฅผ ์ํ ์ํ: O(k), ์ฌ๊ธฐ์ k๋ ๊ณ ์ ๋ฌธ์ ๊ฐ์
45
+ // - ๋ฐ๋ผ์ ์ ์ฒด ์๊ฐ๋ณต์ก๋๋ O(n)
46
+ // ๊ณต๊ฐ๋ณต์ก๋: O(1)
47
+ // - ๋ ๊ฐ์ Map ๊ฐ์ฒด ์์ฑ: mapS์ mapT
48
+ // - ๊ฐ Map์ ์ต๋ k๊ฐ์ ๊ณ ์ ๋ฌธ์๋ฅผ ์ ์ฅ (k๋ ๊ณ ์ ๋ฌธ์ ๊ฐ์)
49
+ // - ์๋ฌธ์ ์๋ฌธ์๋ง ์ฌ์ฉํ๋ฏ๋ก k โค 26 (a-z)
50
+ // - ๋ฐ๋ผ์ ์ ์ฒด ๊ณต๊ฐ๋ณต์ก๋๋ O(1) (์์ ์๊ฐ)
51
+
52
+ // follow up: ์ ๋์ฝ๋ ํ
์คํธ ์ผ์ด์ค. ํฐ ์๋ฏธ๋ ์์
53
+ console . log ( isAnagram ( "๐๐" , "๐๐๐" ) ) ;
54
+ // false
55
+ console . log ( isAnagram ( "ํ๊ธ๊ธ" , "๊ธํ๊ธ" ) ) ;
56
+ // true
57
+ console . log ( isAnagram ( "cafรฉ" , "รฉfac" ) ) ;
58
+ // true
59
+ console . log ( isAnagram ( "Helloไธ็" , "ไธ็Hello" ) ) ;
60
+ // true
61
+ console . log ( isAnagram ( "์๋
ํ์ธ์" , "ํ์ธ์ ์๋
" ) ) ;
62
+ // true
63
+ console . log ( isAnagram ( "Cafรฉ" , "รฉfac" ) ) ;
64
+ // false
65
+ console . log ( isAnagram ( "Cafรฉ" , "รfac" ) ) ;
66
+ // false
0 commit comments