zoukankan      html  css  js  c++  java
  • [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;
    }
  • 相关阅读:
    寻找我的黑客偶像
    20201215 《信息安全专业导论》第三周学习总结
    罗马数字
    base编码
    20201215 王馨瑶 第2周学习总结
    罗马数字转阿拉伯数字
    2020-2021-1 20201226 《信息安全专业导论》第三周学习总结
    IEEE754 浮点数
    Base64
    2020-2021-1 20201226 《信息安全专业导论》第2周学习总结
  • 原文地址:https://www.cnblogs.com/littletail/p/5216596.html
Copyright © 2011-2022 走看看