题目讲解
6. Z 字形变换
算法讲解
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1)return s;
string ret;
int step = 2 * numRows - 2;
int n = s.size();
//记录第一行
for(int i = 0; i < n; i += step)
{
ret += s[i];
}
//处理接下来的行
for(int i = 1; i < numRows - 1; i++)
{
for(int j = i, k = step-i; j < n || k < n; j += step, k += step)
{
if(j < n)ret += s[j];
if(k < n)ret += s[k];
}
}
//处理最后一行
for(int i = numRows - 1; i < n; i += step)
{
ret += s[i];
}
return ret;
}
};