Problem
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H NA P L S I I GY I R
And then read line by line: “PAHNAPLSIIGYIR”.
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example
Input: s = "PAYPALISHIRING", numRows = 3Output: "PAHNAPLSIIGYIR"
Input: s = "PAYPALISHIRING", numRows = 4Output: "PINALSIGYAHRPI"Explanation:P I NA L S I GY A H RP I
Input: s = "A", numRows = 1Output: "A"
Solution
使用一个二维数组,存储每行结果。
var convert = function (s, numRows) {if (numRows === 1) return s;const conversionArr = [];for (let i = 0; i < numRows; i++) {conversionArr.push([]);}for (let i = 0; i < s.length; i++) {const quotient = parseInt(i / (numRows - 1));const remainder = i % (numRows - 1);if (quotient % 2 !== 0) {conversionArr[numRows - remainder - 1].push(s[i]);} else {conversionArr[remainder].push(s[i]);}}let res = "";for (let i = 0; i < conversionArr.length; i++) {for (let ii = 0; ii < conversionArr[i].length; ii++) {res += conversionArr[i][ii];}}return res;};
另一种方式
var convert = function (s, numRows) {
if (numRows === 1) return s;
const rows = [];
for (let i = 0; i < numRows; i++) {
rows.push("");
}
var curRow = 0;
var goingDown = false;
for (let i = 0; i < s.length; i++) {
rows[curRow] += s[i];
if (curRow === 0 || curRow === numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
let res = "";
for (let i = 0; i < rows.length; i++) {
res += rows[i];
}
return res;
};
