问题描述:
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"
.
解题思路:
注意到zigzag的字符串按照读写的顺序是来回分配给不同行的,所以存在取模值的问题,对于正着往下读的字符串,对(nRows-1)取模值的结果刚好是它对应的行数,而对于往上读取的情况,对(nRows-1)取模的结果加上行号刚好等于(nRows-1)。所以考虑用boolean变量记录方向。对于每一行设立StringBuilder对象,适合向其末尾追加值。
代码如下:
public class Solution {
public String convert(String s, int nRows) {
StringBuilder[] stringBuilder = new StringBuilder[nRows];
for(int i = 0; i < nRows; i++)
stringBuilder[i] = new StringBuilder();
boolean reverse = true;
if(nRows == 1)
return s;
if (s.length() == 1)
return s;
for(int i = 0; i < s.length(); ++i){
if(i % (nRows - 1) == 0)
reverse = !reverse;
if(! reverse){
stringBuilder[i % (nRows - 1)].append(s.charAt(i));
}
else{
stringBuilder[nRows - 1 -(i % (nRows - 1))].append(s.charAt(i));
}
}
for(int i = 1; i < nRows; i++){
stringBuilder[0].append(stringBuilder[i]);
}
return stringBuilder[0].toString();
}
}