LeedCode刷题笔记-Z字形变化
题目描述
将一个给定字符串 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”
示例 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
解题代码
class Solution {
public:
string convert(string &s, int &numRows)
{
int len = s.length();
if(len == 1 || numRows == 1)
{
return s;
}
//这里的index是用来存储输出字符的一个下标,add_num是用来计算每一行应该进位的数字
//step是第0行和n - 1行所要前进的位移
int index = 0, add_num = 0, step = numRows * 2 - 2, i = 0;
string ret;
for(i = 0; i < numRows; i++)
{
add_num = i * 2;
index = i;
while(index < len)
{
//这里就是实现了间距交替,先是step - 2 * 行数,再是 2 * 行数
ret += s[index];
add_num = step - add_num;
//最后一行和第一行的间距是不一样的
index += (i == 0 || i == numRows - 1) ? step : add_num;
}
}
return ret;
}
};
方法总结
-
每一行字母的所有下标其实是有规则的
我们先假定有 numRows=4 行来推导下,其中 2numRows-2 = 6 , 我们可以假定为 step=2numRows-2 </,我们先来推导下规则:第0行: 0 - 6 - 12 - 18
==> 下标间距 6 - 6 - 6 ==> 下标间距 step - step - step
第1行: 1 - 5 - 7 - 11 - 13
==>
下标间距 4 - 2 - 4 - 2 ==> 下标间距step-2*1(行)-2 * 1(行)-step-2*1(行)-2*1(行)
第2行: 2 - 4 - 8 - 10 - 14
==>下标间距 2 - 4 - 2 - 4 ==> 下标间距step-2*2(行)-2*2(行)-step-2*2(行)-2*2(行)
第3行:3 - 9 - 15 - 21
==>
下标间距间距 6 - 6 - 6 ==>下标间距step - step - step
可以得出以下结论:
起始下标都是行号
第0层和第numRows-1层的下标间距总是step 。
中间层的下标间距总是step-2行数,2行数交替。
下标不能超过len(s)-1
-
再就是利用规律写代码了,
add_num = i * 2;index = i;
这里把其写在while循环前面,就是为了方便每一次给ret赋不一样的值(中间层的下标间距总是step-2行数,2行数交替)