-
-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathGroupAnagrams.java
56 lines (45 loc) · 1.75 KB
/
GroupAnagrams.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
46
47
48
49
50
51
52
53
54
55
56
package java1.algorithms.strings;
import java.util.*;
public class GroupAnagrams {
//HashMap using sorted strings:- TC:O(n * mlogn) SC:O(n)
private static List<List<String>> groupAnagram(String[] strs) {
Map<String, List<String>> hashMap = new HashMap<>();
for(String str: strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedStr = new String(chars);
if(!hashMap.containsKey(sortedStr)) {
hashMap.put(sortedStr, new ArrayList<>());
}
hashMap.get(sortedStr).add(str);
}
return new ArrayList<>(hashMap.values());
}
//HashMap and char array:- TC:O(n * m) SC:O(n)
private static List<List<String>> groupAnagram1(String[] strs) {
Map<String, List<String>> hashMap = new HashMap<>();
for(String str: strs) {
int[] charsCount = new int[26];
for(char ch: str.toCharArray()) {
charsCount[ch - 'a']++;
}
StringBuilder sb = new StringBuilder();
for(int i=0; i< 26; i++) {
sb.append("*");
sb.append(charsCount[i]);
}
String key = sb.toString();
hashMap.putIfAbsent(key, new ArrayList<>());
hashMap.get(key).add(str);
}
return new ArrayList<>(hashMap.values());
}
public static void main(String[] args) {
String[] strs1 = {"eat","tea","tan","ate","nat","bat"};
System.out.println(groupAnagram(strs1));
System.out.println(groupAnagram1(strs1));
String[] strs2 = {"hello"};
System.out.println(groupAnagram(strs2));
System.out.println(groupAnagram1(strs2));
}
}