File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 9
9
public class _49 {
10
10
11
11
public static class Solution1 {
12
+ /**
13
+ * Time: O(n*k*logk) where n is the # of strings in the given input and k is the maximum length of each string
14
+ */
12
15
public List <List <String >> groupAnagrams (String [] strs ) {
13
16
Map <String , List <String >> map = new HashMap <>();
14
17
for (String word : strs ) {
@@ -23,4 +26,30 @@ public List<List<String>> groupAnagrams(String[] strs) {
23
26
return new ArrayList <>(map .values ());
24
27
}
25
28
}
29
+
30
+ public static class Solution2 {
31
+ /**
32
+ * This is an improvement to the above solution in terms of time complexity.
33
+ * Time: O(n*k) where n is the # of strings in the given input and k is the maximum length of each string
34
+ */
35
+ public List <List <String >> groupAnagrams (String [] strs ) {
36
+ Map <String , List <String >> map = new HashMap <>();
37
+ for (String word : strs ) {
38
+ int [] count = new int [26 ];
39
+ for (char c : word .toCharArray ()) {
40
+ count [c - 'a' ]++;
41
+ }
42
+ StringBuilder sb = new StringBuilder ();
43
+ for (int c : count ) {
44
+ sb .append (c );
45
+ sb .append ("$" );
46
+ }
47
+ if (!map .containsKey (sb .toString ())) {
48
+ map .put (sb .toString (), new ArrayList <>());
49
+ }
50
+ map .get (sb .toString ()).add (word );
51
+ }
52
+ return new ArrayList <>(map .values ());
53
+ }
54
+ }
26
55
}
Original file line number Diff line number Diff line change 12
12
13
13
import static junit .framework .TestCase .assertEquals ;
14
14
import static junit .framework .TestCase .assertTrue ;
15
+ import static org .assertj .core .api .Assertions .assertThat ;
15
16
16
17
public class _49Test {
17
18
private static _49 .Solution1 solution1 ;
You can’t perform that action at this time.
0 commit comments