1. 程式人生 > 實用技巧 >Leetcode Z字形變換

Leetcode Z字形變換

Z子變換

將一個給定字串根據給定的行數,以從上往下、從左到右進行Z 字形排列。

比如輸入字串為 "LEETCODEISHIRING"行數為 3 時,排列如下:

L C I R
E T O E S I I G
E D H N
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:"LCIRETOESIIGEDHN"。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/zigzag-conversion

1、行數為1和2特殊情況單獨處理:

2、一個list管理n行的字串, t和d管理插入到第幾行的字串 ,最後逐行拼接字串

class Solution:
    def convert(self, s: str, numRows: int) -> str:

        if numRows ==1:
            return s
        if numRows==2:
            return s[0::2] + s[1::2]
        final =["" for i in range(numRows)]

        t= 0
        d = 1
        i = 0
        max1 = numRows-2
        while i<len(s):
            


            final[t]+=s[i]
            t+=d
            if d==1 and t>=numRows:
                t = max(numRows-2,0)
                d= -1
            elif d==-1 and t<1:
                t = 0
                d =1
            i+=1
        s1=''
        #print(final)
        for i in range(len(final)):
            s1 +=final[i]
        return s1