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"]
]
Note: For the return value, each inner list's elements must follow the lexicographic order.

Use hash table to keep the strings that shift all elements with length of the first element to 'a' (e.g. 'c' -> 'a' is 2)

    public List<List<String>> groupStrings(String[] strings) {

        List<List<String>> res = new ArrayList();

        if(strings.length == 0) return res;

        HashMap<String, List<String>> map = new HashMap();

        for(String word : strings){

            String key = "";

            int diff = word.charAt(0) - 'a';

            for(int i = 1; i < word.length(); i++){
                key += (word.charAt(i) - diff + 26) % 26;
            }

            List<String> arr = map.getOrDefault(key ,new ArrayList<String>());

            arr.add(word);

            map.put(key, arr);
        }

        for(List<String> list : map.values()){
            Collections.sort(list);
            res.add(list);
        }

        return res;
    }

results matching ""

    No results matching ""