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;
    }
  • 相关阅读:
    Apache日志分析
    iptables日志探秘
    php与其他一些相关工具的安装步骤分享
    ERROR 1 (HY000): Can't create/write to file '/tmp/#sql_830_0.MYI' (Errcode: 13)
    一些可能需要的正则
    restful api的简单理解
    认识MySQL Replication
    如何处理缓存失效、缓存穿透、缓存并发等问题
    经典算法mark
    php常用的一些代码
  • 原文地址:https://www.cnblogs.com/littletail/p/5216596.html
Copyright © 2011-2022 走看看