|
| 1 | +/** |
| 2 | + * @param {string} s |
| 3 | + * @param {number} numRows |
| 4 | + * @return {string} |
| 5 | + */ |
| 6 | + |
| 7 | + |
| 8 | +// const convert = function(s, numRows) { |
| 9 | +// const sArr = s.split(''); |
| 10 | +// let cols = {}; |
| 11 | +// let col = 1; |
| 12 | +// let index = numRows-2; |
| 13 | +// while (sArr.length !== 0) { |
| 14 | +// |
| 15 | +// if (col === 1 || col%(numRows-1) === 1) { |
| 16 | +// if (col !==1) { |
| 17 | +// index = numRows -2; |
| 18 | +// } |
| 19 | +// if (sArr.length <= numRows) { |
| 20 | +// cols[col] = sArr.splice(0, sArr.length); |
| 21 | +// for (let j=cols[col].length; j<numRows; j++) { |
| 22 | +// console.log(j); |
| 23 | +// cols[col][j] = ' '; |
| 24 | +// } |
| 25 | +// console.log(cols[col]); |
| 26 | +// } else { |
| 27 | +// if (numRows<=2) { |
| 28 | +// cols[col] = sArr.splice(0, 1); |
| 29 | +// } else { |
| 30 | +// cols[col] = sArr.splice(0, numRows); |
| 31 | +// } |
| 32 | +// } |
| 33 | +// } else { |
| 34 | +// cols[col] = new Array(numRows).fill(' '); |
| 35 | +// cols[col][index] = sArr.splice(0, 1)[0]; |
| 36 | +// index--; |
| 37 | +// } |
| 38 | +// |
| 39 | +// col ++; |
| 40 | +// |
| 41 | +// } |
| 42 | +// let result = ''; |
| 43 | +// for (let i = 0; i< numRows; i++) { |
| 44 | +// Object.keys(cols).forEach(function(key) { |
| 45 | +// console.log(cols[key]); |
| 46 | +// if (cols[key][i] !== ' ') { |
| 47 | +// result +=cols[key][i]; |
| 48 | +// } |
| 49 | +// }); |
| 50 | +// } |
| 51 | +// return numRows === 1 ? s : result; |
| 52 | +// }; |
| 53 | + |
| 54 | +const convert = function (s, numRows) { |
| 55 | + if(s.length < numRows || numRows < 2 || s.length < 2) { |
| 56 | + return s; |
| 57 | + } |
| 58 | + let returnS = ''; |
| 59 | + // Loop over rows |
| 60 | + for (let j = 0; j < numRows; j++) { |
| 61 | + for (let i = j; i < s.length; i += 2 * (numRows - 1)) { |
| 62 | + returnS += s[i]; |
| 63 | + console.log(s[i]); |
| 64 | + if (j !== 0 && j < numRows - 1) { |
| 65 | + /** |
| 66 | + * Not first row and last row |
| 67 | + * @type {number} |
| 68 | + */ |
| 69 | + const intermediateIndex = i + 2 * (numRows - j - 1); |
| 70 | + if (s[intermediateIndex]) { |
| 71 | + console.log(s[intermediateIndex]); |
| 72 | + returnS += s[intermediateIndex]; |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + return returnS; |
| 78 | +}; |
| 79 | + |
| 80 | +const a = 'PAYPALISHIRING'; |
| 81 | + |
| 82 | +console.log(convert(a, 4)); |
| 83 | + |
| 84 | + |
0 commit comments