Problem
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.
Example:
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Solution
class Solution {
public List<List<String>> groupStrings(String[] strings) {
Map<String, List<String>> map = new HashMap<>();
for (String str: strings) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < str.length(); i++) {
int diff = str.charAt(i)-str.charAt(i-1);
if (diff < 0) diff += 26;
sb.append('a'+diff); //***** 'a' *****
}
String key = sb.toString();
map.putIfAbsent(key, new ArrayList<>());
map.get(key).add(str);
}
return new ArrayList<>(map.values());
}
}
//["an","bcf"]
//keys: 110, 98100
//result: [["an"],["bcf"]]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。