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 class Solution {
public String convert(String s, int numRows) {
String[] strRow = new String[numRows];
int i = 0;
for (i = 0; i < numRows; i++) {
strRow[i] = "";
}
i = 0;
while (i < s.length()) {
for (int j = 0; j < numRows && i < s.length(); j++) {
strRow[j] += s.charAt(i++);
}
for (int k = numRows - 2; k > 0 && i < s.length(); k--) {
strRow[k] += s.charAt(i++);
}
}
String str = "";
for (i = 0; i < numRows; i++) {
str += strRow[i];
}
return str;
}
}