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

2023-12-22 19:49:27

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

文章来源:https://blog.csdn.net/xiaoyang01234/article/details/135159156
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。