-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_249.java
44 lines (36 loc) · 1.38 KB
/
_249.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.fishercoder.solutions.firstthousand;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class _249 {
public static class Solution1 {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> result = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String word : strings) {
// calculate the representative/key that's unique for the entire group
// i.e. if the two string belong to the same group, after shifting n times, they all
// will end up having the same key
// abc -> "2021"
// xyz -> "2021"
// acef -> "212324"
String key = "";
int offset = word.charAt(0) - 'a';
for (int i = 1; i < word.length(); i++) {
char c = word.charAt(i);
int offsetForThisChar = (c - offset + 26) % 26;
key += offsetForThisChar;
}
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(word);
}
for (List<String> list : map.values()) {
result.add(list);
}
return result;
}
}
}