Problem 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)
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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
Code
class Solution {
public String convert(String s, int numRows) {
String[] res = new String[numRows];
for(int i = 0; i < numRows; i++) {
res[i] = "";
}
int len = s.length();
if(len == 0) {
return "";
}
int l = 0;
int point = 0;
while(l < len) {
if(numRows >= 3) {
if(point == 0) {
for(int i = 0; i < numRows; i++) {
if(l == len) {
break;
}
res[point++] += s.charAt(l++);
}
point -= 2;
} else {
res[point--] += s.charAt(l++);
}
} else {
for(int i = 0; i < numRows; i++) {
if(l == len) {
break;
}
res[i] += s.charAt(l++);
}
}
}
String ss = "";
for(int i = 0; i < numRows; i++) {
ss += res[i];
}
return ss;
}
}
Analysis
- String数组主要初始化。