6. ZigZag Conversion

https://leetcode.com/problems/zigzag-conversion/description/
题目大意:给一个字符串和n,要求按n行的“之”字形来输出
解题思路:如下图:

/*n=numRows
Δ=2n-2    0                           2n-2                           4n-4
Δ=        1                     2n-3  2n-1                    4n-5   4n-3
Δ=        2               2n-4        2n                 4n-6         .
Δ=        .             .               .               .             .
Δ=        .       n+1                 .           3n-1                .
Δ=        n-2   n                     3n-4    3n-2                   5n-6
Δ=2n-2    n-1                         3n-3                           5n-5
*/

两列之间的差为2n-2(n为行号),其中除第0行和第n-1行,其余都有“之”字形,如第1行的2n-3,然而两列间差不变,仍为2n-2.中间量的公式为:

  +2(n-1-1)       +2*1
1-----------2n-3----------2n

即第一步+2(n-1-i),第二步+2*i,i为行号。
如此即可。
此外还要考虑特殊情况:numRows=1,此时会进入无限循环,因此要特殊处理。

代码:

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;  //特殊处理
        int len = s.length();
        string result = "";
        for (int i = 0; i < numRows; i++) {
            int step1 = 2*(numRows-1-i);
            int step2 = 2*i;
            int pos = i;
            result += s[pos];
            while (1) {
                pos += step1;
                if (pos >= len) break;
                if (step1) result += s[pos];  //防止重复输出(n=0和n=numRows-1pos += step2;
                if (pos >= len) break;
                if (step2) result += s[pos];  //防止重复输出
            }
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/u012033124/article/details/79857783