- 模拟遍历过程
- 用一个flag记录当前是不是需要从上到下(从下到上)转换方向
- 初始flag设为-1。记录好当前行后,判断是否需要更新flag
- 如果行数为0或1,则直接返回
class Solution(object):
def convert(self, s, numRows):
if numRows < 2: return s
res=["" for i in range(numRows)]
i=0
flag=-1
for c in s:
res[i]+=c
if i==numRows-1 or i==0: flag=-flag
i += flag
return "".join(res)
class Solution {
public:
string convert(string s, int numRows) {
if (numRows < 2) return s;
vector <string> res;
for (int i = 0; i < numRows; ++i) {
res.push_back("");
}
int i = 0;
int flag = -1;
for (auto &c:s) {
res[i] += c;
if (i == 0 || i == numRows - 1) {
flag = -flag;
}
i += flag;
}
string ans = "";
for (auto &c:res) {
ans += c;
}
return ans;
}
};