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"]
]
class Solution {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> ans = new ArrayList<>();
if (strings == null || strings.length == 0) return ans;
Map<String, List<String>> hash = new HashMap<>();
for (String str : strings){
String key = getKey(str);
if (!hash.containsKey(key)){
hash.put(key, new ArrayList<String>());
}
hash.get(key).add(str);
}
return new ArrayList<>(hash.values());
}
private String getKey(String str){
String key = "";
for (int i = 1; i < str.length(); i++){
int diff = str.charAt(i) - str.charAt(i - 1);
if (diff < 0){
diff += 26;
}
key += diff;
}
//System.out.println("str: " + str + " key: " + key);
return key;
}
}