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;
    }
  • 相关阅读:
    三、nginx 编译参数
    二、nginx 安装目录详解
    一、nginx 安装
    CSS未知宽高元素水平垂直居中
    w3c标准盒模型与IE传统模型的区别
    JavaScript设计模式与开发实践:分时函数
    JavaScript设计模式与开发实践:惰性函数
    那些年,前端路上遇到的浏览器兼容问题(一)
    css3的filter属性
    关于Normalize.css
  • 原文地址:https://www.cnblogs.com/littletail/p/5216596.html
Copyright © 2011-2022 走看看