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)

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:

string convert(string s, int numRows);

Examples

Example 1:

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

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

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

Example 3:

Input: s = "A", numRows = 1
Output: "A"

Solution

Method 1 - Create String Array for Each Row

We can break each row into Strings and club them in the end. In java, we use StringBuilder to do that. Here is the gist:

Let n be numRows.

  1. Create an array of n strings, sb[n]
  2. Now start traversing vertically down from 0th row to nth row.
  3. Then we come up vertically n-2 rows.
  4. Keep on doing 2 and 3 till we are at end of of string.

Code

Java
public String convert(String s, int nRows) {
	char[] arr = s.toCharArray();
	int n = s.length();
	StringBuilder[] sb = new StringBuilder[nRows];
	for (int i = 0; i<nRows; i++) {
		sb[i] = new StringBuilder();
	}

	int i = 0;
	while (i < n) {
		// vertically down
		for (int idx = 0; idx<nRows && i<n; idx++) {
			sb[idx].append(arr[i++]);
		}
		// obliquely up; idx=nRows-2, as now we are 1 row higher
		for (int idx = nRows - 2; idx >= 1 && i<n; idx--) {
			sb[idx].append(arr[i++]);
		}
	}
	// combine remaining strings to fist string builder
	for (int idx = 1; idx<sb.length; idx++) {
		sb[0].append(sb[idx]);
	}
	return sb[0].toString();
}