-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroup_Shifted_Strings.java
More file actions
48 lines (39 loc) · 1.58 KB
/
Copy pathGroup_Shifted_Strings.java
File metadata and controls
48 lines (39 loc) · 1.58 KB
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
45
46
47
245. Group Shifted Strings
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:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Note: For the return value, each inner list''s elements must follow the lexicographic order.
public class Solution {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> result = new ArrayList<List<String>>();
HashMap<String, List<String>> d = new HashMap<>();
for(int i = 0; i < strings.length; i++) {
StringBuffer sb = new StringBuffer();
for(int j = 0; j < strings[i].length(); j++) {
sb.append(Integer.toString(((strings[i].charAt(j) - strings[i].charAt(0)) + 26) % 26));
sb.append(" ");
}
String shift = sb.toString();
if(d.containsKey(shift)) {
d.get(shift).add(strings[i]);
} else {
List<String> l = new ArrayList<>();
l.add(strings[i]);
d.put(shift, l);
}
}
for(String s : d.keySet()) {
Collections.sort(d.get(s));
result.add(d.get(s));
}
return result;
}
}