[Locked] Group Shifted Strings

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.

分析:

  由于shift后的字符串只有26种形式,所以思路比较直观,线性遍历一遍,在原集合中再遍历查找这26种形式是否存在

代码:

//根据当前字符串生成按首字母顺序排列的字符串数组
vector<string> generateSS(string str) {
    vector<string> vs;
    //找到基准字符串与当前字符串的shift步骤差
    int i = int('a' - str[0]), j = i + 25;
    for(; i <= j; i++) {
        string s = str;
        //进行shift操作,注意越界情况需要求余
        for(char &c : s)
            c = (c + i - 'a') % 26 + 'a';
        vs.push_back(s);
    }
    return vs;
}
vector<vector<string> > shiftedString(vector<string> strings) {
    vector<vector<string> > vvs;
    //通过map便于O(1)时间查询,以及标志位表明是否已被使用
    unordered_map<string, int> hash;
    for(string str : strings)
        hash.insert(make_pair(str, 1));
    for(auto h : hash) {
        vector<string> vs;
        //已被使用则跳过
        if(h.second == 0)
            continue;
        vector<string> ss = generateSS(h.first);
        for(string str : ss) {
            auto pos = hash.find(str);
            if(pos != hash.end()) {
                pos->second = 0;
                vs.push_back(str);
            }
        }
        vvs.push_back(vs);
    }
    return vvs;
}

 

posted @ 2016-02-27 00:28  CarlGoodman  阅读(156)  评论(0编辑  收藏  举报