249. Group Shifted Strings

https://leetcode.com/problems/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"]
]

只由小写字母组成的字符串可根据它自身字符间的等差pattern做shift,把相同的pattern的归到一组。对每个字符串算pattern,因为只包含小写字母,当字符相差为负时要加26,为方便统一全部加26取模。

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        const auto pattern = [](const string &s) {
            string res;
            for (int i = 1; i < s.length(); ++i) {
                res += to_string((s[i] - s[i - 1] + 26) % 26) + " ";
            }
            return res;
        };
        unordered_map<string, vector<string>> m;
        for (const auto &s : strings) {
            m[pattern(s)].push_back(s);
        }
        vector<vector<string>> res;
        for (const auto &p : m) {
            res.push_back(p.second);
        }
        return res;
    }
};

Last updated