Z字形变换
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
codeType
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
codeType
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
示例 2:
codeType
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
示例 3:
codeType
输入:s = "A", numRows = 1
输出:"A"
提示:
codeType
1 <= s.length <= 1000
s 由英文字母(小写和大写)、',' 和 '.' 组成
1 <= numRows <= 1000
解法:
这题需要意识到周期的存在,只需要找出变化周期,并且按照周期进行遍历构造就可以简化问题。这题遍历的过程可以简化为向下移动numsRows,然后斜向上移动numsRows - 2从而得到周期 = 2 * numsRow - 2
typescript
function convert(s: string, numRows: number): string {
if(numRows < 2) return s // 只有一行
// 需要numRows行数组
// 向下写r个字符,然后斜向上写r-2个字符,所以周期是2r-2
// 所以有n / (2r - 2)向上取整个周期
const n = s.length
const arrs: string[] = new Array(numRows).fill('')
const T = Math.ceil(n / (2 * numRows - 2)) // 周期数
let i = 0
while(i<n){
// 从上往下,移动r次
let j = 0
while(j<numRows && i<n){
arrs[j] += s[i]
i++
j++
}
// 从下往上,移动r-2次
let k = numRows - 2
while(k>0 && i<n){
arrs[k] += s[i]
i++
k--
}
}
let res = ''
for(let i=0; i<numRows; i++){
res += arrs[i]
}
return res
};