forked from Abhinandan323/Programming-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupAnagram.java
45 lines (34 loc) · 1.08 KB
/
GroupAnagram.java
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
39
40
41
42
43
44
45
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GroupAnagrams {
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String currString : strs) {
char[] currStringArray = currString.toCharArray();
Arrays.sort(currStringArray);
String sortedStringKey = new String(currStringArray);
System.out.println(currString + "->" + sortedStringKey);
if(map.containsKey(sortedStringKey)) {
List<String> anaList = map.get(sortedStringKey);
anaList.add(currString);
map.put(sortedStringKey, anaList);
} else {
List<String> anaList = new ArrayList<>();
anaList.add(currString);
map.put(sortedStringKey, anaList);
}
}
System.out.println(map);
List<List<String>> ans = new ArrayList<>();
ans.addAll(map.values());
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arr = {"eat","tea","tan","ate","nat","bat"};
groupAnagrams(arr);
}
}