利用线性表结构省略访问的间隔

6. 题目链接-来源:力扣(LeetCode)(中等)

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:”PAHNAPLSIIGYIR”。

请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
 
示例 1:

输入:s = “PAYPALISHIRING”, numRows = 3
输出:”PAHNAPLSIIGYIR”

####思路:
这个题要是想清楚了存储的方式和方向还是蛮简单的。
首先,先考虑输出顺序,是横向输出,那么我倾向于顺着输出的方向分行存储。这里每一行用List存储就行,不论是LinkedList还是ArrayList区别不大。当然,也可以用 StringBuilder 存储,更为高效。
然后是纵向的存储方式,注意到我们是 Z 字型(其实是一个镜像的 N 字型)输入,纵向输入的时候可以按顺序换行,之后需要往回拐,那么数组就是比较方便的。于是就采用一个链表数组 output[] 来方便我们纵向寻址。
接下来就是确定输入的周期了,比如 numRows = 3的时候,先纵向输入3个字符,再回退1行输入1个字符,总计4个字符。可以归纳,输入的周期 mod = numRows * 2 - 2, 对应的 output[] 中的下标就是字符在字符串中的下标i 对周期 mod 进行求余。
时间复杂度:O(n)
空间复杂度:O(n)

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}

LinkedList<Character>[] output = new LinkedList[numRows];
for (int i = 0; i < numRows; i++) {
output[i] = new LinkedList<>();
}

int mod = numRows * 2 - 2;
int n = s.length();
for (int i = 0; i < n; i++) {
int flag = i % mod;
if (flag < numRows) {
output[flag].add(s.charAt(i));
} else {
output[mod - flag].add(s.charAt(i));
}
}

StringBuilder sb = new StringBuilder();
for (LinkedList<Character> ll : output) {
for (char c : ll) {
sb.append(c);
}
}
return sb.toString();
}
}