-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagramsM2.java
More file actions
42 lines (36 loc) · 1.17 KB
/
Copy pathGroupAnagramsM2.java
File metadata and controls
42 lines (36 loc) · 1.17 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
38
39
40
41
42
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Leetcode problem #49, Group Anagrams
* https://leetcode.com/problems/group-anagrams/
*
* m: length of strs array
* n: avg length of each string in strs array
* Time complexity: O(mn)
* Space complexity: O(mn)
*/
public class GroupAnagramsM2 {
public static void main(String[] args) {
String[] strs = { "eat", "tea", "tan", "ate", "nat", "bat" };
List<List<String>> res = groupAnagram(strs);
System.out.println(res);
}
public static List<List<String>> groupAnagram(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] hash = new char[26];
for (char c : str.toCharArray()) {
hash[c - 'a']++;
}
// We are not using any separators, bcz we using characters instead of integer
// count
String key = new String(hash);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(str);
}
return new ArrayList<>(map.values());
}
}