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"]
]
vector<vector<string>> groupStrings(vector<string>& strings) { // time: O(n * str_len); space: O(n)
unordered_map<string, vector<string> > m;
for (string& str : strings) {
string encode_key;
for (char c : str) {
encode_key += to_string((c - str[0] + 26) % 26) + ",";
}
m[encode_key].push_back(str);
}
vector<vector<string> > res;
for (auto it = m.begin(); it != m.end(); ++it) {
res.push_back(vector<string>(it->second.begin(), it->second.end()));
}
return res;
}
Last updated
Was this helpful?