当前位置:网站首页>6. zigzag transformation

6. zigzag transformation

2022-07-01 03:42:00 Sun_ Sky_ Sea

6. Z Font conversion

Original title link :https://leetcode.cn/problems/zigzag-conversion/

Will a given string s According to the given number of rows numRows , From top to bottom 、 Left to right Z Font arrangement .

For example, the input string is “PAYPALISHIRING” The number of rows is 3 when , Arranged as follows :

P A H N
A P L S I I G
Y I R
after , Your output needs to be read line by line from left to right , Generate a new string , such as :“PAHNAPLSIIGYIR”.

Please implement this function to transform a string into a specified number of lines :

string convert(string s, int numRows);

Example 1:

Input :s = “PAYPALISHIRING”, numRows = 3
Output :“PAHNAPLSIIGYIR”
Example 2:
Input :s = “PAYPALISHIRING”, numRows = 4
Output :“PINALSIGYAHRPI”
explain :
P I N
A L S I G
Y A H R
P I
Example 3:

Input :s = “A”, numRows = 1
Output :“A”

Tips :

1 <= s.length <= 1000
s By the English letters ( Lowercase and upper case )、‘,’ and ‘.’ form
1 <= numRows <= 1000

Their thinking :

Z Character assignment arrangement of shapes , Output is a printout by line , So there is numRows, The string on each line is set to s1,s2...sn, Each character c stay Z The row index corresponding to the shape is from s1 To sn, Then you encounter the first or last line , Change direction from sn To s1, This is repeated . So simulate such repeated operations , Calculate the string of each line , Finally, the answer to the question is to link the strings of all lines in line order .

Code implementation :

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        #  If there is only one line , Go straight back to s
        if numRows < 2:
            return s

        #  Initialize the string of each line to an empty string 
        #  Finally, connect each line 
        res = ['' for _ in range(numRows)]
        i = 0
        #  Reverse direction identification : Top to bottom or bottom to top , Here is the corresponding line 
        flag = -1

        for c in s:
            #  The characters of the current line are organized 
            res[i] += c
            #  If you encounter the first or last line , according to Z shape 
            #  If you need to change lines, change directions 
            if i == 0 or i == numRows - 1:
                flag = -flag
            i += flag

        return ''.join(res)

reference :
https://leetcode.cn/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/

原网站

版权声明
本文为[Sun_ Sky_ Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010323232890.html