将一个给定字符串 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
通过次数283,630提交次数561,283
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
寻找每一行之间的规律
PAYPALISHIRING 3:numRows
P A H N
A P L S I I G
Y I R
0 4 8 12
1 3 5 7 9 11 13
2 6 10
我们可以发现,第一行,都是2*numRows -2 的倍数
最后一行每次增加2*numRows -2,可以抽象表示为 numRows - 1 + i*(2*numRows -2),i表示第几次加
在中间的,奇数行也是每次递增2*numRows -2,
偶数行则是,前一个奇数行的下标值 + [(2*numRows -2)- 2 * (i + 1)]。
i表示当前是中间行的第几行,i从0开始,小于numRows-2.
PAYPALISHIRING 4:numRows
P I N
A L S I G
Y A H R
P I
0 6 12
1 5 7 11 13
2 4 8 10 14
3 9
单独看偶数行
8 = 2 * numRoes - 2
0 8 16
1 7 9 15 (8-2) = 7 - 1 = (8 - 2*(i+1) i = 0
2 6 10 14 (8-4) = 6 - 2 = (8 - 2*(i+1) i = 1
3 5 11 13 (8-6) = 5 - 3 = (8 - 2*(i+1) i = 2
4 12
classSolution{publicStringconvert(String s,int numRows){StringBuffer str =newStringBuffer();int segment =2* numRows -2;int length = s.length();if(length < numRows || numRows ==1){return s;}//头for(int i =0; i < length; i+=segment){
str.append(s.charAt(i));}//体for(int i =0; i < numRows -2; i++){for(int j = i +1; j < length; j+=segment){
str.append(s.charAt(j));if(j + segment -2*(i +1)< length){
str.append(s.charAt(j + segment -2*(i +1)));}}}//尾for(int i = numRows -1; i < length; i+=segment){
str.append(s.charAt(i));}return str.toString();}}