这题就很简单了,4分钟搞定
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"
.
我的实现代码
public static String convert(String s, int numRows) {
int point = numRows - 1, j = 0;
String s0 = "";
int i = point;
if(i == 0) return s;
int margin0 = i << 1;
int margin = 0;
while(i > 0) {
margin = i << 1;
j = point - i;
while(j < s.length()) {
s0 += s.charAt(j);
j += margin;
if(i != point) {
margin = margin0 - margin;
}
}
i--;
}
j = point - i;
margin = j << 1;
while(j < s.length()) {
s0 += s.charAt(j);
j += margin;
}
return s0;
}
大佬的代码:
public static String convert2(String s, int numRows) {
if (numRows==1) return s;
int jumps = numRows*2 - 2; // Number of zigs
StringBuilder ans = new StringBuilder();
for (int j = 0; j < numRows; j++) {
int i = j;
while (i < s.length()) {
ans.append(s.charAt(i));
i += jumps;
if (j != 0 && j != numRows-1 && i - 2*j < s.length()) { // Check that not on first or last row
ans.append(s.charAt(i-2*j));
}
}
}
return ans.toString();
}