- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemo_5.java
More file actions
Latest commit
35 lines (30 loc) · 1.04 KB
/
Copy pathDemo_5.java
File metadata and controls
35 lines (30 loc) · 1.04 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
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
classGroupAnagrams{
publicList<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = newHashMap<>();
for(Stringstr: strs){
char[] arr = str.toCharArray();
Arrays.sort(arr);
StringsortedStr = String.valueOf(arr);
// System.out.println(sortedStr);
if(!map.containsKey(sortedStr)){
map.put(sortedStr, newArrayList<>());
}
map.get(sortedStr).add(str);
}
// System.out.println(map.values());
returnnewArrayList<>(map.values());
}
}
publicclassDemo_5 {
publicstaticvoidmain(String[] args) {
GroupAnagramsga = newGroupAnagrams();
List<List<String>> result = ga.groupAnagrams(newString[]{"eat","tea","tan","ate","nat","bat"});
// Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
System.out.println(result);
}
}