题目如下:
解题思路:
找每一行的等差数组规律,先不考虑字符串各字母内容,找元素下标的规律,如上第二个样例,下标排列如下:
* 0 6 12
* 1 5 7 11 13
* 2 4 8 10 14 16
* 3 9 15
可以看出,除去斜边后每一行都是一个等差数列(如第一行0、6、12;第二行1、7、13),而斜边元素是竖排中的数加上某一个固定差值值(如第二行就是1+4=5、7+4=11;第三行就是2+1=4、8+2=10)。
- 综合可以总结出规律,每一行固定等差数列的差值是 numRows+numRows-2(即 2*numRows-2);
- 然后除第一行和最后一行外,中间每一行要加上变化的数组值,其差值为上一行动态等差数列的差依次减2,因为每向下一行两个数间隔就少两个数,例如第二行固定值 6-2=4,第三行固定值就是 4-2=2。
代码如下:
class Solution {
public:
string convert(string s, int numRows) {
int length = s.size();
int count_fixed = 2*numRows - 2;//每行固定间隔
int count_change = 0;//除第一行和最后一行外,每行中间数的变化间隔
string result = "";
if(length == 0 || length <= numRows || numRows == 1)
return s;
for(int i = 0; i < numRows; i++){
for(int j = i; j < length; ){
result = result + s.at(j);
count_change = count_fixed - i*2;//中间数的变化间隔
if(i != 0 && i != numRows-1 && j+count_change < length){//当不是第一行和最后一行时
result = result + s.at(j + count_change);
}
j = j + count_fixed;
}
}
return result;
}
};