N字形变换(麻烦的方法)

N字形变换(麻烦的方法)_第1张图片

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        #先判断z有多少隔开
        s_new=""
        index_now=0
        if len(s)<=numRows or numRows==1:
            return s
        for i in range(numRows-1,-1,-1):
            exchange=0
            index_exchange=index_now
            s_new+=s[index_now]
            #计算每一层的差距
            gap_buttom=int(1+(i-1)*2)
            gap_top=int(1+(numRows-i-2)*2)
            if i==numRows-1 or i==0:
                while index_exchange+int(1+(numRows-2)*2)+1<=len(s)-1:
                    s_new+=s[index_exchange+int(1+(numRows-2)*2)+1]
                    index_exchange+=int(1+(numRows-2)*2)+1
                index_now+=1
                continue
            while i!=numRows-1 and i!=0:
                if exchange==0:
                    if index_exchange+gap_buttom+1>len(s)-1:
                        index_now+=1
                        break
                    else:
                        s_new+=s[index_exchange+gap_buttom+1]
                        index_exchange+=(gap_buttom+1)
                        exchange=1
                else:
                    if index_exchange+gap_top+1>len(s)-1:
                        index_now+=1
                        break
                    else:
                        s_new+=s[index_exchange+gap_top+1]
                        index_exchange+=(gap_top+1)
                        exchange=0
        return s_new

你可能感兴趣的:(算法,python)