Medium
题目描述
将一个给定字符串 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"
示例 2:
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
示例 3:
输入:s = "A", numRows = 1
输出:"A"
提示:
1 <= s.length <= 1000s由英文字母(小写和大写)、','和'.'组成1 <= numRows <= 1000
解题思路
解题思路
这道题的关键是找到 Z 字形排列的规律。我们可以通过两种方法来解决:
方法一:按行排列(推荐) 观察 Z 字形排列的规律,我们可以直接按行来构建结果。对于每一行,我们找到该行包含的所有字符的索引位置。
Z 字形的周期规律为:cycleLen = 2 * numRows - 2(当 numRows > 1 时)
对于第 i 行(0-indexed):
- 第一类字符:索引为
i + k * cycleLen的字符 - 第二类字符:当
i != 0且i != numRows-1时,还有索引为(k+1) * cycleLen - i的字符
方法二:模拟排列过程 创建 numRows 个字符串,模拟字符填入的过程。使用一个方向标志来控制当前是向下填充还是向上填充。
两种方法的时间复杂度都是 O(n),但方法一的空间复杂度更优,因此推荐使用方法一。
代码实现
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
string result;
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) {
result += s[j + i];
if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) {
result += s[j + cycleLen - i];
}
}
}
return result;
}
};
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
result = []
n = len(s)
cycle_len = 2 * numRows - 2
for i in range(numRows):
j = 0
while j + i < n:
result.append(s[j + i])
if i != 0 and i != numRows - 1 and j + cycle_len - i < n:
result.append(s[j + cycle_len - i])
j += cycle_len
return ''.join(result)
public class Solution {
public string Convert(string s, int numRows) {
if (numRows == 1) return s;
StringBuilder result = 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) {
result.Append(s[j + i]);
if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) {
result.Append(s[j + cycleLen - i]);
}
}
}
return result.ToString();
}
}
var convert = function(s, numRows) {
if (numRows === 1) return s;
const rows = Array(numRows).fill().map(() => []);
let currentRow = 0;
let goingDown = false;
for (let char of s) {
rows[currentRow].push(char);
if (currentRow === 0 || currentRow === numRows - 1) {
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}
return rows.map(row => row.join('')).join('');
};
复杂度分析
| 复杂度类型 | 数值 | 说明 |
|---|---|---|
| 时间复杂度 | O(n) | 需要遍历字符串中的每个字符一次 |
| 空间复杂度 | O(1) | 除了存储结果的空间外,只使用常数额外空间 |