6. ZigZag Conversion
Description
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)

And then read line by line: "PAHNAPLSIIGYIR"
Constraints
Approach
Links
YouTube
Examples
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Explanation:

Solutions
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public String convert(String s, int numRows) {
if(s.length() == 1 || numRows <= 1) return s;
int row = 0;
int n = s.length();
boolean down = true;
String[] arr = new String[n];
Arrays.fill(arr, "");
for(int i = 0; i < n; i++) {
arr[row] += s.charAt(i);
if(row == numRows-1) {
down = false;
} else if(row == 0) {
down = true;
}
if(down) {
row++;
} else {
row--;
}
}
return String.join("", arr);
}
}
Follow up
Last updated
Was this helpful?