6. Zigzag Conversion(Z 字形转换)
题目大意
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);
中文释义
字符串 “PAYPALISHIRING” 按给定行数的 Z 字形排列如上所示(为了更好的可读性,你可能希望以固定字体显示这种模式)。
然后逐行读取:“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 <= 1000
s
由英文字母(小写和大写),‘,’ 和 ‘.’ 组成。1 <= numRows <= 1000
解题思路
使用动态规划(DP)来解决问题。创建多个字符串以存储每一行的字符,并根据 Z 字形规则添加字符。
步骤说明
- 如果
numRows
为 1,则直接返回原字符串。 - 初始化一个字符串向量
rows
,长度为min(numRows, s.size())
。 - 遍历字符串
s
的每个字符:- 将字符添加到当前行
rows[curRow]
。 - 如果当前行是第一行或最后一行,则改变方向。
- 根据方向更新当前行
curRow
。
- 将字符添加到当前行
- 将所有行的字符串连接起来,形成最终结果。
代码
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> rows(min(numRows, int(s.size())));
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) ret += row;
return ret;
}
};