Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Topic describes

Arrange a given string s in zigzagging from top to bottom and left to right, numRows, according to the given number of rows.

For example, if the string “PAYPALISHIRING” is set to 3 rows, it will look like this:

P   A   H   N
A P L S I I G
Y   I   R
Copy the code

After that, your output needs to be read line by line from left to right, producing a new string, such as “PAHNAPLSIIGYIR”.

Implement this function to convert a string to the specified number of lines:

string convert(string s, int numRows);
Copy the code
  • Example 1:
Enter: s ="PAYPALISHIRING", numRows = 3Output:"PAHNAPLSIIGYIR"
Copy the code
  • Example 2:
Enter: s ="PAYPALISHIRING", numRows = 4Output:"PINALSIGYAHRPI"P I N A L S I G Y A H R P ICopy the code
  • Example 3:
Enter: s ="A", numRows = 1Output:"A"
Copy the code
  • Tip:
`1 <= s.length <= 1000`
`s`Consists of letters (lowercase and uppercase),` ', '` 和 ` '`composition`1 <= numRows <= 1000`
Copy the code

Implementation approach

The problem shows that provides a string and the number of rows needed we use string out of the corresponding number of rows of Z last new string, analyse the Z type string we can readily find rule: each string relative to the previous character is not going down to the upper right away, this law can become our judgement. First, we define numRows as an array of strings representing the 0-numrows row, and then iterate over the s string to determine whether the next string goes down or up and right and store it in the corresponding string array. Finally, the string array is converted to a string for the result.

/ * * *@param {string} s
 * @param {number} numRows
 * @return {string}* /
var convert = function(s, numRows) {
    if (numRows == 1) {
        return s
    }
    let resList = new Array(numRows).fill(' ')
    let array = s.split(' ')
    let index = 0   // Array index
    let bool = true // Determine if the character goes down or right
    for(let i = 0; i < array.length; i++) {
        resList[index] += array[i]
        if (bool) {
            index++
        } else {
            index--
        }
        if (index == 0) {   //0 represents the top, which means it's up to the right. It's time to go down
            bool = true
        }
        if (index == numRows - 1) { // numrows-1 means to go to the bottom and up to the right
            bool = false}}return resList.join(' ')};Copy the code