[LeetCode programmer practicing internal strength Series] 6. ZigZag Conversion solution to a problem

Problem Description

String "PAYPALISHIRING"written in zigzag pattern specified number of rows below, it is much like a string in the Z-shaped walking:

P   A   H   N
A P L S I I G
Y   I   R
复制代码

Of strings to be put together again:"PAHNAPLSIIGYIR"

Implementation function string, enter a string and a line number, it returns to the conversion

string convert(string s, int numRows);
复制代码

Example 1:

输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"
复制代码

Example 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:

P     I    N
A   L S  I G
Y A   H R
P     I
复制代码

Difficulty

Medium

Problem-solving ideas

While this question is moderately difficult, but in fact it is very simple solution, according to questions asked, the need to split the original string according to certain rules into n sub-string, then the string is connected to the n th inclusive.

The next question is how to split the original string, and directly see the above example might be easier

原字符串: PAYPALISHIRING
行数: 4
拆分结果: 
[0]: P     I    N
[1]: A   L S  I G
[2]: Y A   H R
[3]: P     I
复制代码

The above four sub-strings respectively represent number 0-4, then we then the tag ID to the original string, each character corresponds to a sequence number

PAYPALISHIRING
01232101232101
复制代码

Law found it, so we can write a program, label number substrings to which it belongs is the original character of each string, then the string is constructed based on the sequence number n th, and finally placing them in ascending order the first connected.

Complex and do so for all of the spatial complexity of O (n), the following code:

def convert(self, s, numRows):
    """
    :type s: str
    :type numRows: int
    :rtype: str
    """
    index = 0
    sign = 1
    zigzag_array = []
    for c in s:
        if index == 0:
            sign = 1
        elif index == numRows - 1:
            sign = -1
        if len(zigzag_array) < index + 1:
            zigzag_array.append("")

        zigzag_array[index] += c
        index += sign
    return "".join(zigzag_array)
复制代码

Original title link

Reproduced in: https: //juejin.im/post/5d011396f265da1bb96fd70c

Guess you like

Origin blog.csdn.net/weixin_34405925/article/details/93165328