两种路子
1.
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> rows(min(numRows, int(s.size()))); // 防止s的长度小于行数
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1) {// 当前行curRow为0或numRows -1时,箭头发生反向转折
goingDown = !goingDown;
}
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) {// 从上到下遍历行
ret += row;
}
return ret;
}
};
这种方法是采用vector<string>对字符串按照numRows的步长从上到下在从下到上遍历一遍,之后重复操作,直到遍历完字符串,之后在把vector<string>中的字符串粘贴到一个新的String类型中就可以了
2.
string convert(string s, int numRows) {
if (numRows == 1) return s;
int step = numRows * 2 - 2; // 间距
int index = 0;// 记录s的下标
int len = s.length();
int add = 0; // 真实的间距
string ret;
for (int i = 0; i < numRows; i++) // i表示行号
{
index = i;
add = i * 2;
while (index < len)//超出字符串长度计算下一层
{
ret += s[index]; // 当前行的第一个字母
add = step - add;// 第一次间距是step -2*i,第二次是2*i,
index += (i == 0 || i == numRows-1) ? step : add; // 0行和最后一行使用step间距,其余使用add间距
}
}
return ret;
}
这种方法是找到每个行之间的关系是来进行输入的