leetcode06.N字形变换

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

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

1
2
3
P   A   H   N
A P L S I I G
Y I R

示例:

1
2
3
P   A   H   N
A P L S I I G
Y I R


分析:

1
按行枚举,flag控制方向

代码

  • C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> lines(numRows);
int flag = 1, i = 0;
for (char c : s) {
lines[i] += c;
i += flag;
if (i == -1 || i == numRows) {
flag = -flag;
i += 2 * flag;
}
}
string res;
for (const string& line: lines) {
res += line;
}

return res;
}
};

[原题链接](6. N 字形变换 - 力扣(Leetcode))

0%