forked from Anuj-Kumar-Sharma/DS-Algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
32 lines (25 loc) · 903 Bytes
/
GroupAnagrams.java
File metadata and controls
32 lines (25 loc) · 903 Bytes
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
package interviewQuestions;
import java.util.*;
public class GroupAnagrams {
public static void main(String[] args) {
String strs[] = { "eat", "tea", "tan", "ate", "nat", "bat" };
List<List<String>> ans = groupAnagrams(strs);
for (List<String> list : ans) {
System.out.println(list);
}
}
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
int count[] = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
}
String key = Arrays.toString(count);
List<String> list = map.getOrDefault(key, new LinkedList<String>());
list.add(s);
map.put(key, list);
}
return new LinkedList<>(map.values());
}
}