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
2 n-1+n-1
3 n-1+n-2
* *
* *
n-1 n-1+2
n-1+1
将2*(numRows - 1)个元素视为一个循环,每个循环中首行和尾行只有一个元素,特殊处理。
对于中间行 i (由0开始) 的两个元素,左右两个元素的下标差距为2*(numRows - 1 - i);
Runtime: 3 ms, faster than 97.85%
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1 ){
return s;
}
int length = s.length();
int loop = 2*(numRows - 1);
StringBuilder res = new StringBuilder();
for (int i = 0; i < numRows;i++){
for(int index = i;index < length;index += loop){
res.append(s.charAt(index));
int index2 = index + 2*(numRows - 1 - i);
if (i > 0 && i < numRows - 1 && index2 < length){
res.append(s.charAt(index2));
}
}
}
return res.toString();
}
}