*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"]
]


 1  public class Solution {
 2     public List<List<String>> groupStrings(String[] strings) {
 3 
 4         List<List<String>> res = new ArrayList<List<String>>();
 5         HashMap<String, List<String>> map = new HashMap<String, List<String>>();
 6 
 7         for(String word : strings){
 8             String key = "";
 9             int offset = word.charAt(0) - 'a';
10             for(int i = 1; i < word.length(); i++){
11                 key += (word.charAt(i) - offset + 26) % 26;
12             }
13 
14             if(!map.containsKey(key)){
15                 map.put(key, new ArrayList<String>());
16             }
17             map.get(key).add(word);
18         }
19 
20         for(List<String> list : map.values()){
21             Collections.sort(list);
22             res.add(list);
23         }
24 
25         return res;
26 
27     }
28 }

reference: https://leetcode.com/discuss/67240/around-13-lines-code-in-java

原文地址:https://www.cnblogs.com/hygeia/p/5074818.html