1

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

linspiration
161 声望53 粉丝