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”.
思路: 用一个字符串数组来存储每一行的字符串,按照“之字型”遍历字符串的时候,更新每一行的字符串的内容。
public class Solution {
public String convert(String s, int numRows) {
StringBuilder[] strs = new StringBuilder[numRows];
int n = s.length();
if (numRows <= 0) return null;
if (n == 0) return "";
if(numRows==1) return s;
for (int i = 0; i < numRows; i++)
strs[i] = new StringBuilder("");
StringBuilder res = new StringBuilder("");
for (int i = 0; i < n;) {
for (int j = 0; i < n && j <= numRows-1; j++) {
strs[j] = strs[j].append(s.charAt(i));
i++;
}
for (int j = numRows - 2; i < n && j > 0; j--) {
strs[j] = strs[j].append(s.charAt(i));
i++;
}
}
for (int k = 0; k < strs.length; k++)
res = res.append(strs[k]);
return res.toString();
}
}