leetcode 6.Z 字形变换
起因:
参考了下文
https://blog.csdn.net/qq_38537503/article/details/95031638
但是我觉得他讲得不是很清除,我决定复述一遍
题目描述
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
思路:
‘Z’可以分为两种类型,一种是竖形,一种是斜形。
- 针对竖型:字符所在行数可以通过index / (numRows - 1) 获得
- 针对斜型:字符所在行数可以通过numRows - 1 - line获得
最后我们只需要知道当前字符是竖型还是斜型,继续观察发现,index/(numRows - 1)是偶数便是竖型;是奇数则是斜型。
因此核心代码实现如下:
for (int i = 0; i < size; i++) {
int category = i / (numRows - 1);
int line = i % (numRows - 1);
if (category % 2 == 0) {//竖排列
temp[line].push_back(s[i]);
}
else {//斜排列
temp[numRows - 1 - line].push_back(s[i]);
}
}
完整代码:
class Solution {
public:
string convert(string s, int numRows) {
vector<string> temp(numRows);
int size = s.size();
//特殊情况
if (numRows == 1) {
return s;
}
//常规情况
for (int i = 0; i < size; i++) {
int category = i / (numRows - 1);
int line = i % (numRows - 1);
if (category % 2 == 0) {//竖排列
temp[line].push_back(s[i]);
}
else {//斜排列
temp[numRows - 1 - line].push_back(s[i]);
}
}
string str;
for (int i = 0; i < numRows; i++) {
str.append(temp[i]);
}
return str;
}
};