思路1 利用字符串list进行转换
我们创建一个字符串数组来存放结果,这个数组的长度就是numofRows。遍历原字符串,不断的将遍历到的字符加载每一行的后面,遇到boundary则改变step的方向。这里的boundary就是0和numofRows-1。
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1 || numRows >= s.size()) return s;
vector<string> res(numRows, "");
int step;
int cur_row = 0;
for (int i = 0; s[i]; i++) {
res[cur_row] += s[i];
if (cur_row == numRows - 1) {
step = -1;
} else if (cur_row == 0) {
step = 1;
}
cur_row += step;
}
string res_str = "";
for (int i = 0; i < res.size(); i++) res_str += res[i];
return res_str;
}
};在python中我们直接用''.join(list_name)的形式把list转换为字符串
Last updated
Was this helpful?