Skip to content

Commit 162ce35

Browse files
refactor 249
1 parent 750c4fc commit 162ce35

File tree

1 file changed

+19
-33
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+19
-33
lines changed

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

Lines changed: 19 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,49 +5,35 @@
55
import java.util.HashMap;
66
import java.util.List;
77
import java.util.Map;
8-
/**Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
98

10-
"abc" -> "bcd" -> ... -> "xyz"
11-
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
12-
13-
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
14-
A solution is:
15-
16-
[
17-
["abc","bcd","xyz"],
18-
["az","ba"],
19-
["acef"],
20-
["a","z"]
21-
]
22-
23-
*/
249
public class _249 {
2510

26-
public List<List<String>> groupStrings(String[] strings) {
11+
public static class Solution1 {
12+
public List<List<String>> groupStrings(String[] strings) {
13+
14+
List<List<String>> result = new ArrayList<List<String>>();
15+
Map<String, List<String>> map = new HashMap<String, List<String>>();
2716

28-
List<List<String>> result = new ArrayList<List<String>>();
29-
Map<String, List<String>> map = new HashMap<String, List<String>>();
17+
for (String word : strings) {
18+
String key = "";
19+
int offset = word.charAt(0) - 'a';
20+
for (int i = 1; i < word.length(); i++) {
21+
key += (word.charAt(i) - offset + 26) % 26;
22+
}
3023

31-
for (String word : strings) {
32-
String key = "";
33-
int offset = word.charAt(0) - 'a';
34-
for (int i = 1; i < word.length(); i++) {
35-
key += (word.charAt(i) - offset + 26) % 26;
24+
if (!map.containsKey(key)) {
25+
map.put(key, new ArrayList<>());
26+
}
27+
map.get(key).add(word);
3628
}
3729

38-
if (!map.containsKey(key)) {
39-
map.put(key, new ArrayList<>());
30+
for (List<String> list : map.values()) {
31+
Collections.sort(list);
32+
result.add(list);
4033
}
41-
map.get(key).add(word);
42-
}
4334

44-
for (List<String> list : map.values()) {
45-
Collections.sort(list);
46-
result.add(list);
35+
return result;
4736
}
48-
49-
return result;
50-
5137
}
5238

5339
}

0 commit comments

Comments
 (0)