Skip to content

Commit f64721e

Browse files
add a solution for 49
1 parent 645684b commit f64721e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/com/fishercoder/solutions/_49.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
public class _49 {
1010

1111
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+
*/
1215
public List<List<String>> groupAnagrams(String[] strs) {
1316
Map<String, List<String>> map = new HashMap<>();
1417
for (String word : strs) {
@@ -23,4 +26,30 @@ public List<List<String>> groupAnagrams(String[] strs) {
2326
return new ArrayList<>(map.values());
2427
}
2528
}
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+
}
2655
}

src/test/java/com/fishercoder/_49Test.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
import static junit.framework.TestCase.assertEquals;
1414
import static junit.framework.TestCase.assertTrue;
15+
import static org.assertj.core.api.Assertions.assertThat;
1516

1617
public class _49Test {
1718
private static _49.Solution1 solution1;

0 commit comments

Comments
 (0)