-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_36.java
More file actions
38 lines (30 loc) · 1.19 KB
/
Problem_36.java
File metadata and controls
38 lines (30 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package strings;
// Given a sequence of words, print all anagrams together
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class Problem_36 {
public static List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> anagramMap = new HashMap<>();
for (String word : strs) {
// Sort the characters of the word (anagrams have the same sorted characters)
char[] charArray = word.toCharArray();
Arrays.sort(charArray);
String sortedWord = new String(charArray);
// Add the word to the list of anagrams for its sorted form (key) in the HashMap
anagramMap.putIfAbsent(sortedWord, new ArrayList<>());
anagramMap.get(sortedWord).add(word);
}
// Convert the HashMap values (lists of anagrams) to a List of Lists for the output
return new ArrayList<>(anagramMap.values());
}
public static void main(String[] args) {
String[] words = {"act", "god", "cat", "dog", "tac"};
List<List<String>> anagramGroups = groupAnagrams(words);
System.out.println("Anagram groups:");
for (List<String> group : anagramGroups) {
System.out.println(group);
}
}
}