ボタン(leetcode 6)のZ等角変換パイソンとどまります

タイトル

所与の行に従って指定した文字列の数は、ダウンに、Z字状の配置から左。

例えば、入力文字列が行の数である「LEETCODEISHIRING」次のように配置し、3:

LCIR
ETOESIIG
EDHNは
「LCIRETOESIIGEDHN」:行右に読み取りラインに左からその後は、次のような、新しい文字列を生成し、出力を必要としています。

あなたは、この行の文字列変換関数指定された数を実現します。

文字列変換(numRowsの数INT文字列s、 );
例1:

入力:S = "LEETCODEISHIRING"、numRowsの数 = 3
出力: "LCIRETOESIIGEDHN"
例2:

入力:S = "LEETCODEISHIRING"、numRowsの数は = 4
出力: "LDREOEIIECIHNTSG"
説明:

LDR
EOEII
ECIHN
TSG

出典:滞在ボタン(LeetCode)
リンク:https://leetcode-cn.com/problems/zigzag-conversion

考え

直接2次元シミュレーションのリストを開きます。

コード

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