当前位置 博文首页 > 向日葵的专属太阳:LeetCode6.Z字形变换(图解算法)

    向日葵的专属太阳:LeetCode6.Z字形变换(图解算法)

    作者:[db:作者] 时间:2021-08-13 22:05

    题目来源:力扣(LeetCode)


    题目描述:
    将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

    比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

    P   A   H   N
    A P L S I I G
    Y   I   R
    

    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如: "PAHNAPLSIIGYIR"

    请你实现这个将字符串进行指定行数变换的函数:

    string convert(string s, int numRows);
    

    示例1:

    输入:s = "PAYPALISHIRING", numRows = 3
    输出:"PAHNAPLSIIGYIR"
    

    示例2:

    输入:s = "PAYPALISHIRING", numRows = 4
    输出:"PINALSIGYAHRPI"
    解释:
    P     I    N
    A   L S  I G
    Y A   H R
    P     I
    

    示例3:

    输入:s = "A", numRows = 1
    输出:"A"
    

    提示:

    • 1 <= s.length <= 1000
    • s 由英文字母(小写和大写)、',''.' 组成
    • 1 <= numRows <= 1000

    解题思路:
    根据题目的描述,能够发现当遍历 s 时,每个字母Z字形图案对应的行索引从 0 ~ numRows-1 ,再从 numRows-1 ~ 0 如此反复。
    因此,解决方案为:模拟这个行索引的变化,在遍历 s 中把每个字符填到正确的行 rst[index] ,最后返回拼接的结果。
    在这里插入图片描述

    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            if numRows == 1:
                return s
            rst = ['' for _ in range(numRows)]
            # index Z字形行索引,flag标志变量
            index, flag = 0, -1
            for char in s:
            	# 将char添加到Z字形对应行
                rst[index] += char
                # 设置转折点0, numRows - 1
                if index == 0 or index == numRows - 1:
                    flag = - flag
                index += flag
            return ''.join(rst)
    

    在这里插入图片描述

    cs