File tree 1 file changed +36
-0
lines changed 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s
3
+ * @param {string } t
4
+ * @return {boolean }
5
+ */
6
+ var isAnagram = function ( s , t ) {
7
+ /*
8
+ // Split string and sort charaters
9
+ // Compare s and t after sorting
10
+ return s.split("").sort().join() === t.split("").sort().join()
11
+ // 92ms, 53.29MB
12
+ */
13
+
14
+ // Made Hashmap and count number of each charater
15
+ let map = { } ;
16
+
17
+ // Check character length between s and t
18
+ if ( s . length !== t . length ) return false ;
19
+ // Put a character and add or substract number
20
+ for ( let i = 0 ; i < s . length ; i ++ ) {
21
+ map [ s [ i ] ] = map [ s [ i ] ] ? map [ s [ i ] ] + 1 : 1 ;
22
+ map [ t [ i ] ] = map [ t [ i ] ] ? map [ t [ i ] ] - 1 : - 1 ;
23
+ }
24
+
25
+ for ( let i = 0 ; i < s . length ; i ++ ) {
26
+ if ( map [ s [ i ] ] !== 0 ) return false ;
27
+ }
28
+
29
+ return true ;
30
+ } ;
31
+
32
+ console . log ( isAnagram ( "anagram" , "nagaram" ) ) ;
33
+ console . log ( isAnagram ( "rat" , "car" ) ) ;
34
+
35
+ // TC: O(n)
36
+ // SC: O(n)
You can’t perform that action at this time.
0 commit comments