[LeetCode] 6. ZigZag Conversion

Problem

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

1
2
3
P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

1
string convert(string s, int numRows);

Example 1:

1
2
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

1
2
3
4
5
6
7
8
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

Explanation

  1. Observing the above example, we can create a stringbuilder array, each stringbuilder representing a row, then asign the value to it character by character.

  2. Start from the first character, while the character index is less than the string length. We first loop from top to bottom, then we loop from second last row to second row. Repeat the first loop then the second loop.

  3. Finally we append all the stringbuilders to one single string and return the string.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public String convert(String s, int numRows) {
        StringBuilder[] sbArr = new StringBuilder[numRows];
        for (int m = 0; m < sbArr.length; m++) {
            sbArr[m] = new StringBuilder();
        }
        int i = 0;
        while (i < s.length()) {
            for (int j = 0; j < numRows && i < s.length(); j++) {
                sbArr[j].append(s.charAt(i++));
            }
            for (int j = numRows - 2; j >= 1 && i < s.length(); j--) {
                sbArr[j].append(s.charAt(i++));
            }
        }
        for (int n = 1; n < sbArr.length; n++) {
            System.out.println(sbArr[n].toString());
            sbArr[0].append(sbArr[n]);
        }
        return sbArr[0].toString();
    }
}