Title description:
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 non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
Example 1:
Input: [“abc”, “bcd”, “acef”, “xyz”, “az”, “ba”, “a”, “z”],
Output:
[
[“abc”,“bcd”,“xyz”],
[“az”,“ba”],
[“acef”],
[“a”,“z”]
]
Time complexity: O()
uses the string whose first letter is'a' as the key for each string of different length. For example, a string with a unique length uses "a" as the key, a string of length 2 "az", "ba" with "az" as the key, and a string of length 3 "abc", "bcd", " "xyz" uses "abc" as the key to observe the relationship between each length of string and key: the difference between each letter of the key string and the string of the same group is the same. For example: the characters "abc", "bcd", and "xyz" with a length of 3 use "abc" as the key. Compare "bcd" and key "abc":'b'-'a' ='c'-'b' ='d'-'c' = offset = 1.
class Solution {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> res = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String str : strings) {
StringBuilder sb = new StringBuilder();
int offset = str.charAt(0) - 'a';
for(int i = 0; i < str.length(); i++){
char c = (char) (str.charAt(i) - offset);
if (c < 'a') {
c += 26;
}
sb.append(c);
}
String key = sb.toString();
map.putIfAbsent(key, new LinkedList<>());
map.get(key).add(str);
}
return new ArrayList<>(map.values());
}
}