Group Shifted Strings

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]

  • Time: O(n)
  • Space: O(1)
public List<List<String>> groupShiftedString(String[] strs) {
    Map<String, List<String>> map = new HashMap<>();
    List<List<String>> ret = new ArrayList<>();
    for (String str : strs) {
        int offset = str.charAt(0) - 'a';
        String key = "";
        for (int i = 1; i < str.length(); i++) {
            key += (str.charAt(i) - offset + 26) % 26;
        }
        if (!map.containsKey(key)) {
            map.put(key, new ArrayList<>());
        }
        map.get(key).add(str);
    }
    for (List<String> value : map.values()) {
        Collections.sort(value);
        ret.add(value);
    }
    return ret;
}

results matching ""

    No results matching ""