249. Group Shifted Strings
https://leetcode.com/problems/group-shifted-strings/
"abc" -> "bcd" -> ... -> "xyz"Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]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