【LeetCode】 6. Z 字形变换
原题
解题思路
对题目的理解
- 字符串
s
是以一个变形的Z
字为顺序存储的,结果需要横向逐行输出。 - 通过第一条,联想到二维数组。数组中有
numRows
个数组,分别为a1 ,a2, a3 ... an,向数组中push
的顺序(行索引)先增大,在减小,再增大.....反复,直至循环到字符串s
结束。 - 综上所诉,定义两个变量,一个控制行号
rowIndex
,向哪一行push
。一个控制方向direction
,向哪个方向push。
show code
function convert(s: string, numRows: number): string {
if (s.length <= numRows || numRows === 1) return s
const resArr = []
const len = s.length
let rowIndex = 0
let direction = 'down' // up / down
function set(rowIndex, val) {
if (!resArr[rowIndex]) resArr[rowIndex] = []
resArr[rowIndex].push(val)
}
for (let strIndex = 0; strIndex < len; strIndex++) {
const r = strIndex % (numRows - 1)
if (r === 0) direction = direction === 'up' ? 'down' : 'up'
set(rowIndex, s[strIndex])
if (direction === 'up') {
rowIndex ++
} else {
rowIndex--
}
}
return resArr.flat(2).join('')
}
console.log(convert("PAYPALISHIRING", 3))
总结
感觉写复杂了,这个得改改~