美文网首页
LeetCode 6. Z 字形变换

LeetCode 6. Z 字形变换

作者: liulei_ahu | 来源:发表于2019-02-21 20:44 被阅读0次

    6. Z 字形变换

    将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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
    

    解题思路
    找规律,以 s = "LEETCODEISHIRINGABCDEFG", numRows = 5为例:

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

    按行读取, 有以下规律:
    第一行数据对应原字符串中的s[0], s[8], s[16]..., 相邻元素之间的索引相差2*4
    第二行数据对应原字符串中的s[1], s[7], s[9],s[15]..., 相邻元素之间的索引相差2*32*1
    第三行数据对应原字符串中的s[2], s[6], s[10],s[14]..., 相邻元素之间的索引相差2*22*2
    第四行数据对应原字符串中的s[3], s[5], s[11],s[13]..., 相邻元素之间的索引相差2*12*3
    第五行数据对应原字符串中的s[4], s[12], s[20]..., 相邻元素之间的索引相差2*4


    代码实现

    class Solution:
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            result = ''
            for i in range(numRows): # 依次处理每一行
                index = i # 每一行第一个字符在原字符串中的索引位置
                flag = True
                while(index < len(s)): # 确保未溢出
                    result += s[index]
                    if flag == True:
                        if numRows - i - 1>0:
                            delt = 2*(numRows-i-1) 
                        else:
                            delt = 2*(numRows-1)
                    else:
                        if numRows - 1 - (numRows - i - 1) >0:
                            delt = 2*(numRows - 1 - (numRows - i - 1)) # 化简即为delt = 2*i
                        else:
                            delt = 2*(numRows-i-1) 
                    if delt == 0: # numRows = 1 情况下的特例
                        delt = 1
                    index = index + delt
                    flag = (flag == False)
                    
            return result
    

    时间复杂度O(n), 空间复杂度O(n)

    相关文章

      网友评论

          本文标题:LeetCode 6. Z 字形变换

          本文链接:https://www.haomeiwen.com/subject/ygodyqtx.html