将一个给定字符串 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"
可以考虑用不同的数组,模拟Z
字 形成的过程,并且在Z
形成的过程中,依次将每一行的字符存到对应的数组中去,最后在从第一行到最后一行依次再存回去。
class Solution {
public:
string convert(string s, int numRows) {
if (s.size() == 1) return s;
int strSize = int(s.size());
int storeSize = min(strSize, numRows);
vector<string> store(storeSize); // 用于储存每一行对应的字符串
int loc = 0; // 用于标识当前所在位置
bool change = false; // 标识是否需要改变方向
string result; // 储存结果
for (int i = 0; i < strSize; i++) { // 遍历 s ,模拟 Z 形成过程
store[loc].push_back(s[i]);
if (loc == numRows-1 || loc == 0) {
// 判断是否需要改变方向:只有在起点和终点才会改变方向
change = !change;
}
loc += change ? 1 : -1;
// 改变方向,相应的需要改变loc的定位方式;
// 如果是向下,就是 + ;反之就是 - 。
}
for (int i = 0; i < storeSize; i++) { // 每行字符串依次拷贝回result
result += store[i];
}
return result;
}
}
LeetCode 6.Z 字形变换