Skip to content

Commit 9979643

Browse files
update 249
1 parent 592320c commit 9979643

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_249.java

+8-2
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,17 @@ public List<List<String>> groupStrings(String[] strings) {
1515
Map<String, List<String>> map = new HashMap<>();
1616

1717
for (String word : strings) {
18+
//calculate the representative/key that's unique for the entire group
19+
//i.e. if the two string belong to the same group, after shifting n times, they all will end up having the same key
20+
// abc -> 2021
21+
// xyz -> 2021
22+
// acef -> 212324
1823
String key = "";
1924
int offset = word.charAt(0) - 'a';
2025
for (int i = 1; i < word.length(); i++) {
21-
key += (word.charAt(i) - offset + 26) % 26;
26+
char c = word.charAt(i);
27+
int offsetForThisChar = (c - offset + 26) % 26;
28+
key += offsetForThisChar;
2229
}
2330

2431
if (!map.containsKey(key)) {
@@ -28,7 +35,6 @@ public List<List<String>> groupStrings(String[] strings) {
2835
}
2936

3037
for (List<String> list : map.values()) {
31-
Collections.sort(list);
3238
result.add(list);
3339
}
3440

Diff for: src/test/java/com/fishercoder/_249Test.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._249;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
6+
7+
import java.util.Arrays;
8+
import java.util.List;
9+
10+
import static org.junit.jupiter.api.Assertions.assertTrue;
11+
12+
public class _249Test {
13+
private static _249.Solution1 solution1;
14+
15+
@BeforeEach
16+
public void setup() {
17+
solution1 = new _249.Solution1();
18+
}
19+
20+
@Test
21+
public void test1() {
22+
List<List<String>> expected = Arrays.asList(Arrays.asList("acef"), Arrays.asList("a", "z"), Arrays.asList("abc", "bcd", "xyz"), Arrays.asList("az", "ba"));
23+
List<List<String>> actual = solution1.groupStrings(new String[]{"abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"});
24+
assertTrue(expected.containsAll(actual));
25+
assertTrue(actual.containsAll(expected));
26+
}
27+
}

0 commit comments

Comments
 (0)