LeetCode 6. Zigzag Conversion
考点 | 难度 |
---|---|
Dynamic Programming | Medium |
题目
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows
思路
用L[idx]
表示下一个字母放到哪一行,从idx
为0开始idx
依次加一,从idx
为numrows - 1
开始idx
依次减一。
答案
class Solution(object):
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s):
return s
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
if index == 0:
step = 1
elif index == numRows -1:
step = -1
index += step
return ''.join(L)