6. ZigZag Conversion
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)
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:
solution 1:
跟随Z字型,遍历String中的每个字符确定所在的rowNumber,需要注意的是遍历到最顶上一行的时候需要调转方向,改为向下;遍历到最下面一行时,同样要调转方向,改为向上。
public String convert(String s, int numRows) {
if (numRows == 1 || s.length() <= numRows) return s;
List<StringBuffer> list = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
list.add(i,new StringBuffer());
}
boolean reverse = false;
int rowNum = 0;
for (int i = 0; i < s.length(); i++) {
list.get(rowNum).append(s.charAt(i));
if (rowNum == 0 || rowNum == numRows-1) reverse = !reverse;
rowNum += reverse? 1:-1;
}
StringBuffer res = new StringBuffer();
for (int i = 0; i < numRows; i++) {
res.append(list.get(i));
}
return res.toString();
}
solution 2:
确定每行都有哪些字符,最后把所有字符拼起来。主要需要解决的问题在于确定每个row中字符在String中的index。
- 第0行
( 2 ∗ r o w N u m − 2 ) ∗ k (2*rowNum - 2)*k (2∗rowNum−2)∗k - 第numRows行
n u m R o w s − 1 + ( 2 ∗ r o w N u m − 2 ) ∗ k numRows - 1 + (2*rowNum - 2)*k numRows−1+(2∗rowNum−2)∗k - 中间的第 i 行
( 2 ∗ r o w N u m − 2 ) ∗ k + i (2*rowNum - 2)*k + i (2∗rowNum−2)∗k+i和 ( 2 ∗ r o w N u m − 2 ) ∗ k + i + 2 ∗ ( n u m R o w s − i − 1 ) = ( k + 1 ) ∗ ( 2 ∗ r o w N u m − 2 ) − i (2*rowNum - 2)*k + i + 2*(numRows - i - 1) = (k+1)*(2*rowNum - 2)-i (2∗rowNum−2)∗k+i+2∗(numRows−i−1)=(k+1)∗(2∗rowNum−2)−i
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
StringBuilder ret = new StringBuilder();
int n = s.length();
int cycleLen = 2 * numRows - 2;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j + i < n; j += cycleLen) {
ret.append(s.charAt(j + i));
if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
ret.append(s.charAt(j + cycleLen - i));
}
}
return ret.toString();
}
}