第6个问题解答里面一个有趣的解法,建立n行,每行是一个vector类的字符串的,然后,从原字符串内往里面一个一个送进字符,每到第一行和尾行就进行转向,转向利用bool类变量进行控制。全部输入完毕之后,重新输出,这种方法更加接近于人类的思考过程:
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)
{
goingDown = !goingDown;
}
curRow += goingDown ? 1: -1;
}
string ret;
for (string row : rows) {// 从上到下遍历行
ret += row;
}
return ret;
}
};