Z transformation

Arrange a given string s in a zigzagging order 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:

PAHNAPLSIIGYIR Then 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);

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/zi… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: traversal

The first step is to determine if the string length is empty or less than 3, or if numRows is 1 (that is, all tiled on one line). Otherwise, iterate over the string’s characters and mark them with a two-dimensional Boolean array in 2 steps. First, go down and no more, then slash to the right. Repeat these 2 steps until all the characters are recorded, and return the result based on the Boolean array’s mark.

public class Solution {
    public static String convert(String s, int numRows) {
        if (s == null || s.length() < 3 || numRows == 1) {
            return s;
        }
        char[][] chars = new char[numRows][s.length()];
        boolean[][] flags = new boolean[numRows][s.length()];

        int x = -1, y = 0, count = 0;
        while (count < s.length()) {
            while (x < numRows && count < s.length()) {
                if (x + 1 < numRows) {
                    x++;
                    chars[x][y] = s.charAt(count);
                    flags[x][y] = true;
                    count++;
                } else {
                    break; }}while (x >= 0 && count < s.length()) {
                if (x - 1> =0) {
                    x--;
                    y++;
                    chars[x][y] = s.charAt(count);
                    flags[x][y] = true;
                    count++;
                } else {
                    break;
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            for (int j = 0; j < chars[i].length; j++) {
                if(flags[i][j]) { sb.append(String.valueOf(chars[i][j])); }}}return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(convert("ABC".1)); }}Copy the code