Skip to content

Commit 5678dcc

Browse files
committed
anagram
1 parent 3cd9f35 commit 5678dcc

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎Medium49.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.*;
2+
3+
public class Medium49 {
4+
public List<List<String>> groupAnagrams(String[] strs) {
5+
if (strs.length == 0) {
6+
return new ArrayList<>();
7+
}
8+
9+
// Use proper generic types for type safety
10+
Map<String, List<String>> ansMap = new HashMap<>();
11+
12+
int[] count = new int[26];
13+
14+
for (String s : strs) {
15+
Arrays.fill(count, 0); // Reset count array for each string
16+
17+
// Count the frequency of each character
18+
for (char c : s.toCharArray()) {
19+
count[c - 'a']++;
20+
}
21+
22+
// Create a unique key based on the character counts
23+
StringBuilder sb = new StringBuilder();
24+
for (int i = 0; i < 26; i++) {
25+
sb.append("#");
26+
sb.append(count[i]);
27+
}
28+
String key = sb.toString();
29+
30+
// If the key doesn't exist, create a new list
31+
ansMap.putIfAbsent(key, new ArrayList<>());
32+
ansMap.get(key).add(s);
33+
}
34+
35+
// Return the grouped anagrams as a list of lists
36+
return new ArrayList<>(ansMap.values());
37+
}
38+
}

0 commit comments

Comments
 (0)