leetcode_algorithm6.ZigZag Conversion

题目:

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

字符串“PAYPALISHIRING”以Z字形图案写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性)

example:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

 思路:

观察每行两个字符在原字符串中的索引的关系,不难发现第一行和第二行每个字符之间的索引间隔为2*(4-1),其他行每个字符之间的索引间隔为(假设行数为i)4-i-1或i+1.先给出求解代码如下:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        
        lens = len(s)
        if lens == 0:
            return ''
        if lens < numRows or lens < 3 or numRows == 1:
            return s
        else:
            i = 0
            flag = 0
            row = 0
            list1 = ''
            current_index = 0
            while i <= lens:
                i = i+1
                list1 = list1 + s[current_index]
                skip_step = 2*(numRows-row-1)
                if 0 < row and row <  numRows - 1:
                    flag = flag + 1
                    if flag % 2 == 0:
                        skip_step = 2*(numRows-1) - skip_step
                if row == numRows - 1:
                    skip_step = 2*(numRows-1) - skip_step
                current_index = current_index + skip_step
                if current_index >= lens:
                    row = row + 1
                    skip_step = 0
                    flag = 0
                    current_index = row
                    if row >= numRows:
                        break
            
            return list1

猜你喜欢

转载自blog.csdn.net/qq_30124241/article/details/88053733