-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemo_5.java
More file actions
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class GroupAnagrams{
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String str: strs){
char[] arr = str.toCharArray();
Arrays.sort(arr);
String sortedStr = String.valueOf(arr);
// System.out.println(sortedStr);
if(!map.containsKey(sortedStr)){
map.put(sortedStr, new ArrayList<>());
}
map.get(sortedStr).add(str);
}
// System.out.println(map.values());
return new ArrayList<>(map.values());
}
}
public class Demo_5 {
public static void main(String[] args) {
GroupAnagrams ga = new GroupAnagrams();
List<List<String>> result = ga.groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"});
// Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
System.out.println(result);
}
}