description
The number of a given string according to the given row, to down, left to right from the Z-shaped arrangement.
Example, the input string is three rows "LEETCODEISHIRING" is arranged as follows:
L C the I R & lt
E T O E S the I the I G
E D H N
after your output required from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".
You will realize this string conversion function specified number of lines:
String Convert For (S String, int numRows);
Example 1
Input: s = "LEETCODEISHIRING", numRows = 3
Output: "LCIRETOESIIGEDHN"
Example 2
Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"
explanation:
L D R & lt
E the OE the I the I
E the I C H N
T G S
answer
var convert = function(s, numRows) {
let arr = []
let j = 0
for(let i = 0; i < numRows; i++){
arr[i] = ''
}
for(let n of s){
j = j >= 2 * (numRows - 1) ? (j - 2 * (numRows - 1)) : j
let k = j > (numRows - 1) ? 2 * (numRows - 1) - j : j
arr[k] += n
j++
}
return numRows === 1 ? s : arr.join('')
};
analysis
Time complexity: O (n), the spatial complexity: O (n)