This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

background

Learning the front end of three months, ready to brush interview questions, summary summary, a few interview questions a day, to the big factory.

“Z shape transformation” is a medium difficulty problem in the force buckle, but after reading this article, you will find that the medium difficulty problem, but also so!

The problem

Z transformation

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:

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

Implement the function that transforms a string to the specified number of lines.

Example 1:

Enter: s = “PAYPALISHIRING”, numRows = 4

Output: “PINALSIGYAHRPI”

parsing

Let’s look at the graph and analyze it:

Ideas:

1: If there is only one line, we return the string directly.

  1. When we analyze the graph, we can see that at line 0 or (numrows-1) the direction of the z-shaped arrow changes. That’s the boundary we’re looking for.

3. We need to identify the number of rows, we at the time of traversal string, can according to the boundary (0 | | numRow – 1) to set the current line increasing, or decreasing.

  1. One other thing to notice is that when we look at the output, it’s a sorted array, and we read it line by line, regardless of the number mismatch. Just add the numbers in the non-vertical rows.

Let’s look at the code:

    / * * *@param {string} s
 * @param {number} numRows
 * @return {string}* /
var convert = function(s, numRows) {
    if(numRows===1 || s.length<=1) return s;
    // Intercepts a string and converts it to an array
    var strArr=s.split("");
    // Set the initial behavior to 0
    var curRow=0;
    // Set the direction downward. The direction controls whether the curRow increment or decrement
    var isDown=false;
    / / store
    var cacheArr=[];
    for(var i=0; i<strArr.length; i++){// Take the current line and initialize it
        cacheArr[curRow]=cacheArr[curRow] || [];
        / / add
        cacheArr[curRow].push(strArr[i]);
        // Critical point, change direction
        if(curRow===0 || curRow === numRows-1){ isDown=! isDown; }// Determine whether the number of rows is increasing or decreasing by direction.
        curRow +=(isDown? 1: -1);
    }
    
    str="";
    // go through the number group
    for(var j=0; j<cacheArr.length; j++){// Array to string
        str+=cacheArr[j].join("");
    }
    return str;
};
Copy the code

Validation:

Code execution renderings:

conclusion

One step at a time, solid work!