Skip to content

Commit 47134c5

Browse files
authored
Update readme.md
1 parent 1f2ffd2 commit 47134c5

File tree

1 file changed

+49
-1
lines changed
  • src/main/java/g0001_0100/s0049_group_anagrams

1 file changed

+49
-1
lines changed

src/main/java/g0001_0100/s0049_group_anagrams/readme.md

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,52 @@ Given an array of strings `strs`, group the anagrams together. You can return th
3232

3333
* <code>1 <= strs.length <= 10<sup>4</sup></code>
3434
* `0 <= strs[i].length <= 100`
35-
* `strs[i]` consists of lowercase English letters.
35+
* `strs[i]` consists of lowercase English letters.
36+
37+
To solve the "Group Anagrams" problem in Java with the Solution class, follow these steps:
38+
39+
1. Define a method `groupAnagrams` in the `Solution` class that takes an array of strings `strs` as input and returns a list of lists of strings.
40+
2. Initialize an empty HashMap to store the groups of anagrams. The key will be the sorted string, and the value will be a list of strings.
41+
3. Iterate through each string `str` in the input array `strs`.
42+
4. Sort the characters of the current string `str` to create a key for the HashMap.
43+
5. Check if the sorted string exists as a key in the HashMap:
44+
- If it does, add the original string `str` to the corresponding list of strings.
45+
- If it doesn't, create a new entry in the HashMap with the sorted string as the key and a new list containing `str` as the value.
46+
6. After iterating through all strings, return the values of the HashMap as the result.
47+
48+
Here's the implementation of the `groupAnagrams` method in Java:
49+
50+
```java
51+
import java.util.*;
52+
53+
class Solution {
54+
public List<List<String>> groupAnagrams(String[] strs) {
55+
// Initialize a HashMap to store the groups of anagrams
56+
Map<String, List<String>> anagramGroups = new HashMap<>();
57+
58+
// Iterate through each string in the input array
59+
for (String str : strs) {
60+
// Sort the characters of the current string
61+
char[] chars = str.toCharArray();
62+
Arrays.sort(chars);
63+
String sortedStr = new String(chars);
64+
65+
// Check if the sorted string exists as a key in the HashMap
66+
if (anagramGroups.containsKey(sortedStr)) {
67+
// If it does, add the original string to the corresponding list
68+
anagramGroups.get(sortedStr).add(str);
69+
} else {
70+
// If it doesn't, create a new entry in the HashMap
71+
List<String> group = new ArrayList<>();
72+
group.add(str);
73+
anagramGroups.put(sortedStr, group);
74+
}
75+
}
76+
77+
// Return the values of the HashMap as the result
78+
return new ArrayList<>(anagramGroups.values());
79+
}
80+
}
81+
```
82+
83+
This implementation ensures that all anagrams are grouped together efficiently using a HashMap.

0 commit comments

Comments
 (0)