Group Shifted Strings -- LeetCode

时间:2023-03-10 02:46:13
Group Shifted Strings -- LeetCode

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.

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

[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
 class Solution {
public:
string help(string word) {
for (int i = , n = word.size(); i < n; i++) {
word[i] = word[i] - word[] + 'a';
while (word[i] < 'a') word[i] += ;
}
word[] = 'a';
return word;
}
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<string, int> dict;
vector<vector<string> > res;
for (int i = , n = strings.size(); i < n; i++) {
string base = help(strings[i]);
if (dict.count(base) == ) {
dict.insert(make_pair(base, res.size()));
vector<string> subGroup(, strings[i]);
res.push_back(subGroup);
}
else res[dict[base]].push_back(strings[i]);
}
return res;
}
};