Question

Formatted question description: https://leetcode.ca/all/249.html

 249	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.

Algorithm

The relative distance between each letter of the string and the first character is equal.

For example, abc and efg are mutually offset. For abc, the distance between b and a is 1, and the distance between c and a is 2. For efg, the distance between f and e is 1, and the distance between g and e is 2. .

Let’s look at another example. The distance between az and yx, z and a is 25, and the distance between x and y is also 25 (direct subtraction is -1, which is the reason for adding 26 and taking the remainder).

Then, in this case, all strings that are offset from each other have a unique distance difference. According to this, the mapping can be well grouped.

Code

Java

import java.util.*;

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

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

            if (strings == null || strings.length == 0) {
                return result;
            }

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

            for (String str : strings) {
                String key = findKey(str);
                if (map.containsKey(key)) {
                    map.get(key).add(str);
                } else {
                    List<String> list = new ArrayList<>();
                    list.add(str);
                    map.put(key, list);
                }
            }

            // iterate the map
            result.addAll(map.values());

            return result;
        }

        private String findKey(String str) {
            // @note: should check for empty string
            if (str.length() == 0) {
                return "";
            }

            StringBuilder sb = new StringBuilder();

            int distance = str.charAt(0) - 'a'; // @note: key is shifting word to start with 'a'

            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                char offset = (char) (c - distance);
                if (offset < 'a') {
                    offset = (char) (offset + 26);
                }
                sb.append(offset);
            }

            return sb.toString();
        }
    }
}

All Problems

All Solutions