leetcode/src/s0006_zigzag_conversion.cpp

52 lines
1.3 KiB
C++

#include "s0006_zigzag_conversion.hpp"
// 简单地找规律
// n = 3
// 0 4 8 12 2*(n-1) * col
// 1 3 5 ... (n-1) * col + 1
// 2 6 10 2*(n-1) * col + (n-1)
// n = 4
// 0 6 12 2*(n-1)*col
// 1 5 7 11 2*(n-1)*col+row, 2*(n-1)*col-row
// 2 4 8 10 2*(n-1)*col+row, 2*(n-1)*col-row
// 3 9 2*(n-1)*col + (n-1)
string S0006::convert(string s, int numRows) {
string r = "";
int l = s.length();
if (l == 1 || numRows == 1) {
return s;
}
for (int col = 0; 2 * (numRows - 1) * col < l; col++) {
r += s[2 * (numRows - 1) * col];
}
if (numRows >= 3) {
for (int row = 1; row < numRows - 1; row++) {
for (int col = 0;; col++) {
if (col == 0) {
if (2 * (numRows - 1) * col + row < l) {
r += s[2 * (numRows - 1) * col + row];
}
} else {
if (2 * (numRows - 1) * col - row < l) {
r += s[2 * (numRows - 1) * col - row];
} else {
break;
}
if (2 * (numRows - 1) * col + row < l) {
r += s[2 * (numRows - 1) * col + row];
} else {
break;
}
}
}
}
}
for (int col = 0; 2 * (numRows - 1) * col + (numRows - 1) < l; col++) {
r += s[2 * (numRows - 1) * col + (numRows - 1)];
}
return r;
}