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.

Example:

Input:
["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

Solution

(1) Java

class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> rst = new ArrayList<>();
        if (strings.length == 0) {
            return rst;
        }
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strings) {
            StringBuilder sb = new StringBuilder();
            char[] chars = str.toCharArray();
            int shift = -1;
            for (char c : chars) {
                if (shift == -1) {
                    shift = 'z'-c+1;
                }
                sb.append((char)((c+shift)%26));
            }
            String key = sb.toString();
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<String>());
            }
            map.get(key).add(str);
        }
        for (List<String> l : map.values()) {
            rst.add(l);
        }
        return rst;
    }
}

(2) Python



(3) Scala



results matching ""

    No results matching ""