力扣(leetcode 6)z形变换 python

题目

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:

L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);
示例 1:

输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2:

输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:

L D R
E O E I I
E C I H N
T S G

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion

思路

直接开个二维列表模拟。

代码

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        l=len(s)
        if l==1 or numRows==1:
            return s
        lie=l//(numRows*2-2)*(numRows-1)
        yu=l%(numRows*2-2)
        if yu<=numRows:
            lie+=1
        else:
            lie=lie +1 +yu-numRows
        ans=[['']*lie for _ in range(numRows)]
        i=0
        hang,x,y=0,0,0
        #print(ans)
        while(i<l):
            if hang<numRows:
                ans[hang][x]=s[i]
                hang+=1
                if hang==numRows:
                    x+=1
                    y=numRows-2
            elif  y!=0:
                ans[y][x]=s[i]
                y-=1
                x+=1
            if hang==numRows and y==0:
                hang=0
            i+=1
        res=""
        for ll in range(numRows):
            for hh in range(lie):
                if ans[ll][hh]!=' ':
                    res=res+ans[ll][hh]
        return res
        
                

猜你喜欢

转载自blog.csdn.net/qq_41318002/article/details/93524367