题目描述
将一个给定字符串 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);
个人解法
JavaScript
var convert = function (s, numRows) {const arr = [];if(numRows === 1){return s;}for (let i = 0; i < numRows; i++) {arr.push([]);}const length = s.length;let up = false;let index = 0;let arrIndex = 0;while (index < length) {arr[arrIndex].push(s[index]);if (up) {arrIndex--;} else {arrIndex++;}if (arrIndex === 0) {up = false;} else if (arrIndex === numRows - 1) {up = true;}index++;}let result = '';for (let i = 0; i < numRows; i++) {result += arr[i].join('');}return result;};
Java
更优解法
JavaScript
/*** @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;};
