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".
題目分析:返回一個字符串的類似于"Z"字形走法碳默,沒有想到什么別的方法船老。模擬步驟走一遍就能得出結果裙戏。
public String convert(String s, int numRows) {
if (s == null)
return null;
if (s.length() <= 1)
return s;
StringBuffer[] sbs = new StringBuffer[numRows];
for (int i = 0; i < sbs.length; i++) {
sbs[i] = new StringBuffer();
}
int j = 0;
while (j < s.length()) {
for (int i = 0; i < numRows; i++) {
if (j < s.length()) {
char c = s.charAt(j++);
sbs[i].append(c);
} else {
break;
}
}
for (int l = numRows - 2; l > 0; l--) {
if (j < s.length()) {
char c = s.charAt(j++);
sbs[l].append(c);
} else {
break;
}
}
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < numRows; i++) {
sb.append(sbs[i]);
}
return sb.toString();
}