原题
https://leetcode.cn/problems/zigzag-conversion/
思路
字符串处理,用方向变量来标记方向。
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def convert(self, s: str, numRows: int) -> str:
# 特殊情况
if len(s) <= 2:
return s
l = [[] for i in range(numRows)]
# 初始化方向
direction = 1
i = 0
for ch in s:
l[i].append(ch)
# 确定下一步的方向
if direction == 1 and i+1 == numRows:
direction = -direction
elif direction == -1 and i-1 < 0:
direction = -direction
i += direction
ans = ''
for row in l:
ans += ''.join(row)
return ans
Java代码
class Solution {
public String convert(String s, int numRows) {
// 基础情况
if (numRows < 2)
return s;
// 初始化列表
List<StringBuffer> rows = new ArrayList<StringBuffer>();
for (int i = 0; i < numRows; i++) {
rows.add(new StringBuffer());
}
int i = 0, flag = -1;
for (char ch: s.toCharArray()) {
rows.get(i).append(ch);
if (i == 0 || i == numRows-1)
// 转向
flag = - flag;
i += flag;
}
// 处理结果字符串
StringBuffer ans = new StringBuffer();
for (StringBuffer row: rows)
ans.append(row);
return ans.toString();
}
}