-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupAnagrams.java
42 lines (36 loc) · 1.05 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
package array;
import java.util.*;
/**
* @author Shogo Akiyama
* Solved on 06/03/2020
* Time: 8m
*
* 49. Group Anagrams
* https://leetcode.com/problems/group-anagrams/
* difficulty: Medium
*
* Approach: Hash Map and Sort
* Runtime: 6 ms, faster than 96.99% of Java online submissions for Group Anagrams.
* Memory Usage: 42.3 MB, less than 90.64% of Java online submissions for Group Anagrams.
*
* Time Complexity: O(n * klog(k))
* Space Complexity: O(n * k)
* Where n is the numbers of elements in the array and k is the maximum length of a string
*
* @see ArrayTest#testGroupAnagrams()
*/
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
if (!map.containsKey(sorted)) {
map.put(sorted, new ArrayList<String>());
}
map.get(sorted).add(s);
}
return new ArrayList<List<String>>(map.values());
}
}