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;
}
原文地址:https://www.cnblogs.com/luo-c/p/12897820.html