leetcode Problem 6: Z-shaped Transform - Simulation Solution Direct Method

[Title] Description
will be given a number of lines according to a given string to down, left to right from the Z-shaped arrangement.
Example, the input string is the number of rows "LEETCODEISHIRING" is 3, arranged as follows:

After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".
You will realize this string conversion function specified number of lines:
String Convert For (S String, int numRows);

[Solving ideas]
For Z-shaped, each row using a StringBuiler to record, so get an array StringBuiler [numRows]; up through the array subscripts y, record the current direction, to start the simulation Z-shaped configuration.

[Code]

String convert(String s, int numRows) {
    if (numRows == 1) {
        return s;
    }

    StringBuilder[] builders = new StringBuilder[numRows];
    for (int i = 0; i < numRows; i++) {
        builders[i] = new StringBuilder();
    }

    // 核心代码快
    char[] arr = s.toCharArray();
    int y = 0;
    boolean up = false;
    for (int i = 0; i < arr.length; i++) {
        builders[y].append(arr[i]);
        if (up) { // 自下向上
            y--;
            if (y == -1) {
                y = 1;
                up = false;
            }
        } else { // 自上向下
            y++;
            if (y == numRows) {
                y = numRows - 2;
                up = true;
            }
        }
    }

    StringBuilder result = new StringBuilder(numRows);
    for (StringBuilder b: builders) {
        result.append(b.toString());
    }

    return result.toString();
}

[Results] run
time execution: 6 ms, beat the 85.36% of all users in java submission;
memory consumption: 39 MB, defeated 93.94% of all users in java submission.

[Summary]
the efficiency of the algorithm needs to be improved, but easier to understand. If everyone a good view, please add.

Guess you like

Origin www.cnblogs.com/qinvis/p/11974291.html