forked from dharmanshu1921/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GroupAnagrams
41 lines (39 loc) · 1.33 KB
/
GroupAnagrams
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
import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
int n = strs.length;
List<List<String>> al = new ArrayList<>();
HashMap<String, ArrayList<String>> hm = new HashMap<>();
for(int i=0; i<n; i++){
char a[] = strs[i].toCharArray();
Arrays.sort(a);
String sorted = new String(a);
// check whether the list for keyword is present
ArrayList<String> alternateList = hm.get(sorted);
if(alternateList == null) {
alternateList = new ArrayList<>();
hm.put(sorted, alternateList);
}
alternateList.add(strs[i]);
}
for (Map.Entry<String,ArrayList<String>> hash : hm.entrySet()) {
al.add(hash.getValue());
}
return al;
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array: ");
int n = sc.nextInt();
System.out.print("Enter array elements: ");
String arr[] = new String[n];
for(int i=0; i<n; i++){
arr[i] = sc.next();
}
Solution obj = new Solution();
List<List<String>> ans = obj.groupAnagrams(arr);
System.out.print(ans);
}
}