一、题目
将一个给定字符串 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来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/zigzag-conversion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
第一想法是建一个二维数组,模拟Z字形操作,然后循环遍历,空间O(n*m),时间O(n*m)
第二个想法,就是Z字形排列,是可以根据规律计算出每一行的每个输出字符的下标的,计算出来之后,直接按照行输出就行,下边是以nrows=4为例子,当nrows>1时,每行的第一个字符对应的下标就是行号,然后每行的第二个字符下标和第一个下标的差距是2*numRows-2*i,其中i对应的是行号;然后之后的下标差距是period = 2*numRows-2-period==0?period:2*numRows-2-period; 需要单独处理一下nrows=1的情况,直接返回原字符串即可
三、通过代码
class Solution {
public String convert(String s, int numRows) {
//numRows=1的情况单独处理
if(numRows==1){
return s;
}
char[] res = new char[s.length()];
int idx=0;
for(int i=1;i<=numRows;i++){
//当前下标值
int curIdx=i-1;
//与下一个下标的差值
int period = 2*numRows-2*i==0?2*numRows-2:2*numRows-2*i;
while(true){
if(curIdx>=s.length() || idx>=s.length()){
break;
}
res[idx++]=s.charAt(curIdx);
curIdx += period;
period = 2*numRows-2-period==0?period:2*numRows-2-period;
}
}
return new String(res);
}
}