Skip to content

Commit 5efddd3

Browse files
committedJun 20, 2022
2022-06-20 update: added "Group Anagrams"
1 parent 1bb6ea3 commit 5efddd3

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import java.util.*;
4+
5+
// https://leetcode.com/problems/group-anagrams/
6+
public class GroupAnagrams {
7+
8+
private final String[] input;
9+
10+
public GroupAnagrams(String[] input) {
11+
this.input = input;
12+
}
13+
14+
public List<List<String>> solution() {
15+
Map<String, List<String>> values = new HashMap<>();
16+
for (String str : input) {
17+
char[] key = new char[str.length()];
18+
for (int i = 0; i < str.length(); i++) {
19+
key[i] = str.charAt(i);
20+
}
21+
Arrays.sort(key);
22+
String k = String.valueOf(key);
23+
if (values.containsKey(k)) {
24+
values.get(k).add(str);
25+
} else {
26+
List<String> value = new ArrayList<>();
27+
value.add(str);
28+
values.put(k, value);
29+
}
30+
}
31+
List<List<String>> result = new ArrayList<>();
32+
for (Map.Entry<String, List<String>> value : values.entrySet()) {
33+
result.add(value.getValue());
34+
}
35+
return result;
36+
}
37+
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import java.util.List;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class GroupAnagramsTest {
10+
11+
@Test
12+
public void defaultTest() {
13+
assertEquals(
14+
List.of(List.of("eat", "tea", "ate"), List.of("bat"), List.of("tan", "nat")),
15+
new GroupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}).solution()
16+
);
17+
}
18+
19+
}

0 commit comments

Comments
 (0)