Thursday, January 7, 2021

LeetCode: ZigZag Conversion

 Problem statement is taken from leet code as it is:

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

 

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"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000

My solution :

package madwani.sushil.leetcode.Jan1_7_2021;
public class ZigZagConversion {
public static void main(String[] args) {
System.out.println(convert("AB", 1));
}

public static String convert(String s, int numRows) {
// obvious, if no of rows are 1 or string is empty return as it is
if (numRows == 1 || s == null) {
return s;
}

// to find out how many cols needed
int col = 0;

// to hold real pattern
char[][] pattern = new char[numRows][1000];

for (int row = 0, i =0; i < s.length() ; row++, i++) {
// start filling the pattern array
pattern[row][col] = s.charAt(i);

// once you reached to the max numbers of rows ( -1 as array index starts with 0 )
if ( row == numRows - 1) {
while (row > 0 && ++i < s.length()) {
// start filling in reverse order, till you reach the top or length of string is exhausted
pattern[--row][++col] = s.charAt(i);
}
}
}
// done print it.
return printString(pattern, s.length(), numRows, col+1);
}

public static String printString(char[][] pattern, int length, int numRows, int numCols) {
StringBuilder result = new StringBuilder(numRows*numCols);
for (int row =0; row < numRows ; row++) {
for (int col =0 ; col < numCols; col++) {
if (pattern[row][col] != '\u0000')
result.append(pattern[row][col]);
}
}
return result.toString();
}
}

No comments: