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"
.
numRows:4;
count :0123432101234......
numRows:3;
count012101210.....
public class Solution {
public String convert(String s, int numRows) {
if (numRows == 1){
return s;
}
String ans = "";
char[] chars = s.toCharArray();
String[] data = new String[numRows];
for (int i = 0; i<numRows; i++){
data[i] = "";
}
int count = 0;
boolean dircetion = true; //true为前,false为后。
for (int i = 0; i<chars.length; i++){
data[count] = data[count] + chars[i];
//System.out.println(data[count]+" "+count);
//System.out.println(count);
if (dircetion){
if (count != numRows-1) count++;
else {
dircetion = false;
count--;
}
}else{
if (count != 0 ) count--;
else{
dircetion = true;
count++;
}
}
}
for (int i = 0; i<numRows; i++){
ans += data[i];
}
return ans;
}
}