6. Zigzag Conversion
2026/1/12大约 1 分钟约 345 字
6. Zigzag Conversion
难度: Medium
题目描述
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
Example 3:
Input: s = "A", numRows = 1 Output: "A"
Constraints:
1 <= s.length <= 1000sconsists of English letters (lower-case and upper-case),','and'.'.1 <= numRows <= 1000
解题思路
代码实现
解决方案
java
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numRows; i++) {
int j = i;
while (j < s.length()) {
if (i == 0 || i == numRows - 1) {
sb.append(s.charAt(j));
//System.out.print(s.charAt(j));
j = j + 2 * (numRows - 1);
} else {
sb.append(s.charAt(j));
// System.out.print(s.charAt(j));
j = j + 2 * (numRows - 1);
if (j - 2 * i < s.length()) {
sb.append(s.charAt(j - 2 * i));
//System.out.print(s.charAt(j - 2 * (i)));
}
}
}
}
//System.out.println(sb.toString());
return sb.toString();
}
}