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)
1 2 3 4
> 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:
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3 Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4 Output: “PINALSIGYAHRPI” Explanation:
1 2 3 4 5
> > > P I N > > > A L S I G > > > Y A H R > > > P I > > >
publicclassSolution{ public String convert(String s, int numRows){ int len = s.length(); if (len < 2 || numRows == 1) { return s; } StringBuffer result = new StringBuffer(""); int last = len % (numRows + numRows - 2); int nums = len / (numRows + numRows - 2); //分组数 int m = nums * (1 + numRows - 2); if (last > numRows) { m += 1 + (last - numRows); } else { m += 1; } char[][] temp = newchar[m][numRows]; boolean flag = true; int a = 0, b = 0; for (int i = 0; i < len; i++) { temp[a][b] = s.charAt(i); if (flag) { ++b; } else { ++a; --b; } if (b == (numRows - 1)) { flag = false; } elseif (b == 0) { flag = true; } }
for (int i = 0; i < numRows; i++) { for (int j = 0; j < m; j++) { String ss = String.valueOf(temp[j][i]); if (!ss.equals("\u0000")) { result.append(ss); } } } return result.toString(); } }
publicclassSolution{ public String convert(String s, int numRows){ if (s == null || s.length() == 0) { return""; } if (s.length() == 1) { return s; } if (numRows <= 1) { return s; } int stringLength = s.length(); char[] chars = s.toCharArray(); char[] output = newchar[stringLength]; int outputIndex = 0;
for (int offset = 0; offset < numRows; offset++) { int index = offset;
// Add the first letter if (index >= stringLength) { break; } output[outputIndex++] = chars[index];
while (index < stringLength) { // Skip this for the last row, since it will // output the same spot if (offset < numRows - 1) { index += 2 * (numRows - 1 - offset); if (index >= stringLength) break; output[outputIndex++] = chars[index]; }
// Skip this for the first row, since it will // always output the same spot if (offset > 0) { index += 2 * offset; if (index >= stringLength) break; output[outputIndex++] = chars[index]; } } } returnnew String(output); // rows = 4 // 0 (2 * rows - 1) // 6 // 12