6 — ZigZag Conversion
1. 题目描述
2. 思路
分析题目:
- 遍历字符串, 确定有几行, 确定每个字符在第几行。 两个转折点:在第0行和第numRows-1行处,要改变方向,也就是curRow变量加一还是减一。
3. Python代码:
def convert(s: str, numRows: int):
rowLength = min(len(s), numRows)
rows = []
if numRows == 1: return s
else :
for i in range(rowLength):
rows.append('')
goDown = False
curRow = 0
for i in range(len(s)):
rows[curRow] += s[i]
if curRow == 0 or curRow == numRows - 1:
goDown = not goDown
if goDown: curRow += 1
else: curRow -=1
res = ''
for i in range(rowLength):
res += rows[i]
return res
4. Complexity Analysis:
Time complexity : O(nnn). 这里的 n == len(s)
Space complexity : O(nnn).