In the Leetcode Zigzag Conversion problem solution in Java programming 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);
Leetcode Zigzag Conversion problem solution in Java programming
public class Solution {
public String convert(String s, int numRows) {
String res="";
List<String> strow = new ArrayList<>();
for(int i=0; i<numRows; i++){
strow.add(0, "");
}
int row=0;
boolean turn=false;
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
String news = strow.get(row)+String.valueOf(c);
strow.remove(row);
strow.add(row,news);
if(!turn)
row++;
else{
row--;
}
row=row%numRows;
if(row==0 && !turn){
row=numRows-2;
if(row<0)
row=0;
turn^= true;
}
if(row==0 && turn){
row=0;
turn^= true;
}
}
for(String st: strow){
res=res+st;
}
return res;
}
}
Also read,
- Leetcode Zigzag Conversion problem solution in C
- Leetcode Zigzag Conversion problem solution in C++
- Leetcode Zigzag Conversion problem solution in Python
- Leetcode Zigzag Conversion problem solution in C#