zoukankan      html  css  js  c++  java
  • 6.ZigZag Conversion

    给定一个之字形排列的字符串,给定排成numRows行,要求按行输出。

    Input: s = "PAYPALISHIRING", numRows = 4
    Output: "PINALSIGYAHRPI"


    思路:

     黑色的数字,每一列都是相差 6。而红色的数字,与它前面的黑色数字,存在如下关系。

    规律:
    这题主要是找关系,之字形的排列,怎么将规律转换到行上,第一行、最后一行大家应该都能找到,重点在于中间的那些行,看似没规律,但其实也和第一行一样,注意第一行中存在字符的位置所在的列,这些列上的间隔和第一行一样,都是 2*(numRows-1),而至于列与列中间的,非首尾行,都存在且只存在一个数,而这个数与旁边列的间隔为: 2*(numRows - x - 1),其中 x 表示第 x 行(下标从0开始)。数组中的下标为: j+ 2*(numRows - x - 1);然后将 j += 2*(numRows-1),继续循环,非首尾行,每一个循环读2个字符.。首尾行单独处理。

    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        int n = s.size();
        string res = "";
        for (int i = 0; i < numRows; i++) {
            int j = i;
            if (i == 0 || i == numRows - 1) { //首尾行单独处理
                while (j < n) {
                    res += s[j];
                    j += 2 * (numRows - 1);
                }
            }
            else {
                while (j < n) {
                    res += s[j];
                    int next = j + 2 * (numRows - (i + 1));//非首尾行中,列与列之间的数的下标
                    if (next < n) res += s[next];
                    j += 2 * (numRows - 1);
                }
            }
        }
        return res;
    }
  • 相关阅读:
    c++ 队列
    17:特殊类成员:函数指针5
    c++ deque 双端队列
    18:字符串-char型字符串
    c++ 16 this 和 继承 及继承机制中的构造函数 与 析构函数
    c++ string char* const char*
    c++ 小片段
    google protobuf 使用示例
    hibernate-cache
    hibernate-criteria查询(二)
  • 原文地址:https://www.cnblogs.com/luo-c/p/12897820.html
Copyright © 2011-2022 走看看