Skip to content

Commit 27f6370

Browse files
committed
feat : group-anagrams
1 parent 8b0b142 commit 27f6370

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

group-anagrams/ekgns33.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
3+
input : array of strings
4+
output : grouped anagrams
5+
6+
ex) eat ate tea > same group
7+
8+
solution 1) brute force
9+
ds : hashmap
10+
algo : sort
11+
generate Key by sorting string O(nlogn)
12+
13+
save to hashmap
14+
15+
tc : O(m* nlogn) when m is length of array, n is max length of string
16+
sc : O(m)
17+
18+
solutino 2) better?
19+
cannot optimize m times read
20+
how about generating key
21+
22+
sort = nlogn
23+
read = n << use frequency
24+
26 * n
25+
tc : O(m * (26 * n)) ~= O(mn)
26+
sc : O(m * 26) ~= O(m)
27+
*/
28+
29+
class Solution {
30+
public List<List<String>> groupAnagrams(String[] strs) {
31+
Map<String, List<String>> map = new HashMap<>();
32+
int n = strs.length;
33+
for(String str : strs) {
34+
int l = str.length();
35+
char[] freq = new char[26];
36+
for(int i = 0; i < l; i++) {
37+
freq[str.charAt(i) - 'a']++;
38+
}
39+
String key = new String(freq);
40+
map.putIfAbsent(key, new ArrayList<>());
41+
map.get(key).add(str);
42+
}
43+
return List.copyOf(map.values());
44+
}
45+
}

0 commit comments

Comments
 (0)