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

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

Lines changed: 8 additions & 2 deletions
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

Lines changed: 27 additions & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy