LeetCode6.Z字形变换

问题描述:


解题思路:

创建一个具有numRows个元素的空列表,设置row=0,step=1,row+=step,一直到第numRows个元素,设置step=-1,直到回到row==0,循环以上步骤。

代码实现:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        
        if numRows == 1 or numRows >= len(s):
            return s
        
        zigzag = [""]*numRows
        
        row, step = 0, 1
        for c in s:
            zigzag[row] += c
            if row == 0:
                step = 1
            elif row == numRows - 1:
                step = -1
            row += step
        
        return "".join(zigzag)

 

猜你喜欢

转载自blog.csdn.net/qq_41689620/article/details/89101324