算法 6.Z字形变换
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
if(numRows == 1) return s
const len = Math.min(s.length, numRows)
const rows = []
// 每行初始化
for(let i = 0; i < len; i++){
rows[i] = ""
}
// 记录行数
let loc = 0
// 记录遍历的方向(上/下)
let down = false
for(const c of s){
// 单行字符串的拼接
rows[loc] += c
// 如果到达顶部或者底部,改变方向
if(loc === 0 || loc === numRows - 1){
down = !down
}
loc += down ? 1 : -1
}
// 最后将所有字符串进行拼接
let ans = ""
for(const row of rows){
ans += row
}
return ans