class Solution {
public:
string convert(string s, int numRows) {
//index指向原字符串s
int index = 0,len = s.size();
string res;
int col = 1;//在第几行
int count = 0;//每一行下标开始位置
int padding = 2*(numRows - 1);
//特殊情况判定
if(numRows == 1)return s;
//从z字行中的第一行依次将字符加入res字符串中
for(int i = 0;i < len;i ++){
res.push_back(s[index]);
//若当前行不是最上或最下的行
if(col != 1 && col != numRows){
//规律是从下至上的2 4 6..详见下面示意
int p = 2*(numRows - col);
if(i+ 1 < len && index + p < len){
res.push_back(s[index + p]);
i ++;//指向res尾部标加1
}
}
//最上和最小两行的水平距离都是padding
index = index + padding;
//若超出则将index指向下一行的启始位置1 2 3 .. numRows
if(index >= len){
index = ++count;
col++; //行数加1
}
}
return res;
}
};
1 5 +4
2 4 6 +2 2*(3 - 2) = 2
3 7
1 7 +6
2 6 8 +4 +2 2*(4 - 2) = 4
3 5 9 +2 +4
4 10
1 +8
2 8 +6
3 7 +4
4 6 +2
5
leetcode6
最新推荐文章于 2024-07-24 19:35:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)