Description
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".
解:
考虑ABCDEFGHIJKLMN
,分为4行的情况,如下:
两个蓝色框中对应行的元素相差2*numRows - 2
,同时除去第一行和最后一行,中间的行会在两个蓝色框直接多一个元素。考察元素F,F与B相差了多少,则可以考察F与它的后一个元素H的差值。
- F到H得距离始终为H到H所在列顶元素距离的2倍,因此F的前一个元素B到F得距离可表示为
2*numRows - 2 - 2*i
,
java代码:
class Solution {
public String convert(String s, int numRows) {
if (numRows < 2) return s;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numRows; i++){
for (int j = i; j < s.length(); j += 2*numRows - 2){
sb.append(s.charAt(j));
if ((i > 0 && i < numRows - 1) && (j + 2*numRows - 2 - 2*i < s.length())){
sb.append(s.charAt(j + 2*numRows - 2 - 2*i));
}
}
}
return sb.toString();
}
}