0
点赞
收藏
分享

微信扫一扫

无人机制造工艺流程详解

caoxingyu 2024-07-29 阅读 28
  1. Zigzag Conversion

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   N
A P L S I I G
Y   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 1:

**Input:** s = "PAYPALISHIRING", numRows = 3
**Output:** "PAHNAPLSIIGYIR"

Example 2:

**Input:** s = "PAYPALISHIRING", numRows = 4
**Output:** "PINALSIGYAHRPI"
**Explanation:**
P     I    N
A   L S  I G
Y A   H R
P     I

Example 3:

**Input:** s = "A", numRows = 1
**Output:** "A"

Constraints:

  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000
JavaScript Solution
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function (s, numRows) {
    // create array with 'numRows' length and empty text
    const arr = new Array(numRows).fill('')
    
    // add letters to the correct arrays
    let count = 0
    while (count < s.length) {
        let m = numRows
        // 1 step: here we create the first column, 
        // so we will add one letter to the every array
        if (m === numRows) {
            for (let i = 0; i < numRows; i++) {
                if (s[count] === undefined) break
                arr[i] += s[count]
                count += 1
            }
            m--
        }
        // 2 step: 
        // here create the zigzag form and add one letter to the one array
        if (m < numRows) {
            while (m > 1) {
                if (s[count] === undefined) break
                arr[m - 1] += s[count]
                count += 1
                m--
            }
        }
    }

    // join the text in the array
    let result = ''
    for (let i = 0; i < arr.length; i++) {
        result += arr[i]
    }
    return result
};
举报

相关推荐

0 条评论