难度:中等。
没啥技巧,就是找规律。可以从周期来考虑,以下述红框内的为一个周期。按照这个周期来找更具体地规律。
正确解法:
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
if(len < 2 || numRows < 2)return s;
int midde_num = numRows - 2;
int z_num = numRows + midde_num;
int period_cols = numRows - 1;
int max_cols = len / z_num * period_cols + midde_num + 1;
string new_string;
for(int row = 0; row < numRows; row++){
for(int col = 0; col < max_cols; col++){
int temp_col = col % period_cols;
int period_num = col / period_cols;
if(temp_col == 0){
int index = z_num * period_num + row;
if(index < len){
new_string += s[index];
}
}
else{
int temp = numRows - row - 1;
if(col == period_num * period_cols + temp){
int index = z_num * period_num + numRows + temp - 1;
if(index < len){
new_string += s[index];
}
}
}
}
}
return new_string;
}
};