-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagram.java
More file actions
37 lines (30 loc) · 1.08 KB
/
GroupAnagram.java
File metadata and controls
37 lines (30 loc) · 1.08 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
import java.util.*;
public class GroupAnagram {
public static String sort(String s){
char[] ch = s.toCharArray();
Arrays.sort(ch);
return new String(ch);
}
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new LinkedList();
List<String> list = new LinkedList<>();
HashMap<String, List<String>> map= new HashMap<>();
for(int i =0; i<strs.length; i++){
if(!map.containsKey(sort(strs[i]))){
map.put(sort(strs[i]), new LinkedList<>());
}
}
for(int i=0; i<strs.length; i++){
map.get(sort(strs[i])).add(strs[i]);
}
for(Map.Entry<String, List<String>> e: map.entrySet()){
res.add(e.getValue());
}
System.out.println(res);
return res;
}
public static void main(String args[]){
String[] strs={"eat","tea","tan","ate","nat","bat"};
groupAnagrams(strs);
}
}