https://leetcode.com/problems/zigzag-conversion/description/
The gist of the title: Given a string and n, it is required to output according to the "zi" glyph of n lines. Problem-
solving ideas: as shown below:
/*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
*/
The difference between the two columns is 2n-2 (n is the row number), except for the 0th row and the n-1th row, the rest have a "zigzag" shape, such as 2n-3 in the 1st row, but between the two columns The difference remains unchanged and is still 2n-2. The formula for the intermediate quantity is:
+2(n-1-1) +2*1
1-----------2n-3----------2n
That is, the first step+2(n-1-i), the second step+2*i, i is the row number.
That's it.
In addition, special cases must be considered: numRows=1, which will enter an infinite loop, so special treatment is required.
Code:
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-1)
pos += step2;
if (pos >= len) break;
if (step2) result += s[pos]; //防止重复输出
}
}
return result;
}
};