题目
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
图片
示例 3:
输入:s = “A”, numRows = 1
输出:“A”
提示:
1 <= s.length <= 1000
s 由英文字母(小写和大写)、’,’ 和 ‘.’ 组成
1 <= numRows <= 1000
答案
自解
class Solution {
public:
string convert(string s, int numRows) {
string ans;
if(numRows == 1)
return s;
for(int offset = 0; offset <= numRows-1; offset++) {
for (int i=0;i<s.size();i+=(numRows - 1) * 2) {
if(offset == 0) {
ans += s[i];
}
else if(offset == numRows - 1) {
if (i + numRows - 1 < s.size())
ans += s[i + numRows - 1];
}
else {
if (i + offset < s.size())
ans += s[i + offset];
if (i + (numRows - 1) * 2 - offset < s.size())
ans += s[i + (numRows - 1) * 2 - offset];
}
}
}
return ans;
}
};
//rows = 3
// 0 4 8 (rows - 1) *2*n
// 1 3 5 7 9 (rows - 1) *2 * n - 1 (rows - 1) *2 * n + 1
// 2 6 10 (rows - 1) *2*n + (rows-1)
//rows = 4
// 0 6 12 (rows - 1) *2 * n
// 1 5 7 11 13 (rows - 1) *2 * n - 1 (rows - 1) *2 * n + 1
// 2 4 8 10 14 (rows - 1) *2 * n - 2 (rows - 1) *2 * n + 2
// 3 9 15 (rows - 1) *2*n + (rows-1)
// rows = 5
// 0 8 16 (rows - 1) *2 * n
// 1 7 9 15 17 (rows - 1) *2 * n - 1 (rows - 1) *2 * n + 1
// 2 6 10 14 18 (rows - 1) *2 * n - 2 (rows - 1) *2 * n + 2
// 3 5 11 13 19
// 4 12 20