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"
class Solution {
public String convert(String s, int numRows) {
int words=s.length();
int noCols=0;
while(words>0) {
words=words-numRows;
noCols=noCols+1;
if(words>0) {
int temp=(numRows-2);
if(temp>0) {
noCols=noCols+(numRows-2);
words=words-temp;
}
}
}
char[][] arr=new char[numRows][noCols];
int j=0;
int k=0;
int even=0;
for(int i=0;i<noCols;i++) {
if(even==0 && k<s.length()) {
j=0;
while(j<arr.length && k<s.length()) {
arr[j][i]=s.charAt(k);
k++;
j++;
}
even=1;
}else {
if(numRows<=2) {
j=0;
while(i<noCols&&j<arr.length && k<s.length()) {
arr[j][i]=s.charAt(k);
k++;
j++;
}
}else {
j=j-2;
while(i<noCols&&j>0 && k<s.length()) {
arr[j][i]=s.charAt(k);
k++;
j--;
}
}
even=0;
}
}
String str="";
for(int i=0;i<numRows;i++) {
for(int l=0;l<noCols;l++) {
if(arr[i][l]!='\u0000') {
str=str+arr[i][l];
}
}
}
return str;
}
}