题目:
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"] ]
思路:
我们将字符串的每个字符都减去一个统一的值,使得首字符变为‘a’,这样可以相互转换的字符就转化成了一个key,然后用map以这个key保存所有可以相互转换的字符串的集合,最后再输出结果。在实现中,我们既可以采用使用哈希表实现的unordered_map,也可以采用使用二叉搜索树实现的map。
代码:
class Solution {
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<string, vector<string>> hash;
for (auto s : strings) {
hash[getGroupKey(s)].push_back(s);
}
vector<vector<string>> ret;
for (auto it = hash.begin(); it != hash.end(); ++it) {
vector<string> line(it->second.begin(), it->second.end());
ret.push_back(line);
}
return ret;
}
private:
string getGroupKey(string &s) {
string ret(s);
int offset = s[0] - 'a';
for (int i = 0; i < s.length(); ++i) {
ret[i] = ret[i] - offset;
if (ret[i] < 'a') {
ret[i] += 26;
}
}
return ret;
}
};