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 RAnd 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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
solution:
public class Solution {
public String convert(String s, int nRows) {
String result = "";
int temp = nRows*2-2;
if(temp == 0){
return s;
}
String[] str = new String[nRows];
for(int i =0 ;i<nRows;i++){
str[i] = "";
}
for(int j=0;j<s.length();j++){
int minJ = j/temp*temp+nRows;
int maxJ = j/temp*temp+temp;
if(j>=minJ && j<maxJ){
int row = nRows-1-j%(nRows-1);
str[row] = str[row]+s.charAt(j);
}else{
int row = j%temp;
str[row] = str[row]+s.charAt(j);
}
}
for(int i =0;i<nRows;i++){
result = result+str[i];
}
return result;
}
}