导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-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)

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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

翻译

给出行数,字符串”PAYPALISHIRING”按照zigzag模式写出来如下:(你可能需要用优化的字体来显示该模式以获得更好的辨识)
P   A   H   N
A P L S I I G
Y   I   R
然后按行读出:”PAHNAPLSIIGYIR”
编写代码,将给定字符串按照指定行数转换:string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) 应当返回 “PAHNAPLSIIGYIR”。

当nRows = 5时,写出如下zigzag模式:
1     9      17
2   8 10   16 18
3  7  11  15  19
4 6   12 14   20
5     13     21
从中可以观察得到,对于第一行和最后一行,每隔 8 (= nRows - 2)个字符循环一次;而对于其他行,除了该循环之外,还包括一个 2 nRows - 2 - 2 row 的循环,直接遍历,需要注意当nRows = 1时直接返回:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public String convert(String s, int nRows) {
if (s == null || s.length() == 0 || nRows <= 1)
return s;
String zStr = "";
int len = s.length();
for (int row = 0; row < nRows; row++) {
int index = row;
while (index < len) {
zStr += s.charAt(index);
if (row != 0 && row != nRows - 1) {
index += 2 * nRows - 2 - 2 * row;
if (index < len)
zStr += s.charAt(index);
index += 2 * row;
} else index += 2 * nRows - 2;
}
}
return zStr;
}
}