1
1
// n: length of strs, m: length of strs[i]
2
- // Time complexity: O(nmlogm )
2
+ // Time complexity: O(nm )
3
3
// Space complexity: O(n)
4
4
5
5
/**
@@ -10,21 +10,29 @@ var groupAnagrams = function (strs) {
10
10
const answer = [ ] ;
11
11
const anagramDict = new Map ( ) ;
12
12
13
- const sortedStrs = strs . map ( ( str ) => {
14
- const splitted = str . split ( "" ) ;
15
- splitted . sort ( ) ;
16
- return splitted . join ( "" ) ;
17
- } ) ;
13
+ const getKey = ( str ) => {
14
+ const counter = Array . from (
15
+ { length : "z" . charCodeAt ( ) - "a" . charCodeAt ( ) + 1 } ,
16
+ ( ) => 0
17
+ ) ;
18
18
19
- for ( let i = 0 ; i < sortedStrs . length ; i ++ ) {
20
- const sortedStr = sortedStrs [ i ] ;
21
- const originalStr = strs [ i ] ;
19
+ for ( const chr of str ) {
20
+ const index = chr . charCodeAt ( ) - "a" . charCodeAt ( ) ;
21
+ counter [ index ] ++ ;
22
+ }
23
+
24
+ return counter . join ( "#" ) ;
25
+ } ;
26
+
27
+ for ( let i = 0 ; i < strs . length ; i ++ ) {
28
+ const str = strs [ i ] ;
29
+ const key = getKey ( str ) ;
22
30
23
- if ( ! anagramDict . has ( sortedStr ) ) {
24
- anagramDict . set ( sortedStr , [ ] ) ;
31
+ if ( ! anagramDict . has ( key ) ) {
32
+ anagramDict . set ( key , [ ] ) ;
25
33
}
26
34
27
- anagramDict . get ( sortedStr ) . push ( originalStr ) ;
35
+ anagramDict . get ( key ) . push ( str ) ;
28
36
}
29
37
30
38
for ( const [ _ , value ] of anagramDict ) {
0 commit comments