6.z-字形变换

时游小于 1 分钟LeetCode

6.z-字形变换

/*
 * @lc app=leetcode.cn id=6 lang=typescript
 *
 * [6] Z 字形变换
 */

// @lc code=start
function convert(s: string, numRows: number): string {
	if (numRows <= 1 || numRows >= s.length) {
		return s;
	}
	let col = Math.ceil(s.length / numRows);
	let arr = Array.from({ length: numRows }, () =>
		Array.from({ length: col }, () => "")
	);

	let currentRow = 0;
	let currentCol = 0;
	let arrow = 0;
	for (let i = 0; i < s.length; i++) {
		// 首行
		if (currentRow == 0) {
			// 向下
			arrow = 0;
		}
		// 尾行
		if (currentRow == numRows - 1) {
			// 斜上
			arrow = 1;
		}

        // 插入值
		arr[currentRow][currentCol] = s[i];


        // 处理数据
		if (arrow == 0) {
			// 向下
			currentRow++;
		}
		if (arrow == 1) {
			// 斜向上
			currentRow--;
			currentCol++;
		}
	}
	// 结果
	let res: string = "";
	res = arr.reduce((acc, row) => acc + row.join(""), "");

	return res;
}

console.log(convert("abcdefghigkl", 4));

// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...