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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
一道数学题目,如下
1 7 13
2 6 8 12 14 18
3 5 9 11 15 17
4 10 16
第一行与最后一行:等差数列,公差为(numRows - 1) * 2等差数列,公差为(numRows - 1) * 2
其他行:以第一个为准,偶数位置与上一个数字的差为(numRows - line -1) * 2,奇数位置与上一个数字差为line * 2;相当于往下走一个来回,得到一个数,再往上走一个来回,得到下一个。以此循环
class Solution {
public String convert(String s, int numRows) {
String ans = "";
if (s.isEmpty() || numRows == 1)
return s;
int line = 0;
while (line < numRows) {
int cur = line;
//先把行首字母放入
if (cur < s.length()){
ans += String.valueOf(s.charAt(cur));
}
while (cur < s.length()){
//当该行是首行或末行的时候,两个数字之间的差为(numRows - 1) * 2
if (line == 0 || line == numRows -1){
cur += (numRows - 1) * 2;
if (cur < s.length()){
ans += String.valueOf(s.charAt(cur));
}
} else{
//不是首行或者末行,想往下走一个来回,得到下一个数
cur += (numRows - line -1) * 2;
if (cur < s.length()){
ans += String.valueOf(s.charAt(cur));
}
//再往上走一个来回
cur += line * 2;
if (cur < s.length()){
ans += String.valueOf(s.charAt(cur));
}
}
}
line++;
}
return ans;
}
}