[LeetCode249]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.

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

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
Note: For the return value, each inner list's elements must follow the lexicographic order.

Hide Company Tags Uber
Hide Tags Hash Table String
Hide Similar Problems (M) Group Anagrams

这种group xxx的题, 都想到hashtable key是这些string 的共同特点,vector里就装这些string自己。
本题的key就是这些字母之间的关系,shift无非就是每个字母之间的gap是一样的。
比如”abc”, “bcd”, “xyz”之间都是1。所以我把它们对应“011“这个key。
但是, 注意到”az” and “ba”是一个group的,按照上面的分析,az应该对应26-1 = 25, ba对应 1-2 = -1。如何让-1 == 25?加个26啊。。。
所以code如下:

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        unordered_map<string, vector<string>> mp;
        for(string s : strings){
            mp[preProcess(s)].push_back(s);
        }
        vector<vector<string>> res;
        for(auto m : mp){
            vector<string> tmp = m.second;
            sort(tmp.begin(), tmp.end());
            res.push_back(tmp);
        }
        return res;
    }
    string preProcess(string s){
        string res;
        for (int i = 1; i<s.size(); ++i) {
            int tmp = s[i] - s[i-1] >= 0 ? s[i] - s[i-1] : s[i] - s[i-1]+26;
            res += 'a' + tmp;
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode)