王廷瑋|數位醫療|智慧醫療: 6. Zigzag Conversion WFU

2024年7月2日 星期二

6. Zigzag Conversion

6. Zigzag Conversion


字符串 "PAYPALISHIRING" 被以如下所示的鋸齒形圖案按指定的行數排列:(為了更好的可讀性,你可能需要將這個圖案顯示在固定寬度的字體中)

P    A    H   N

A P L S  I  I G

Y    I     R

然後按行讀取:"PAHNAPLSIIGYIR"
撰寫代碼,該代碼將接收一個字符串並根據給定的行數進行這種轉換:


Python


class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s

# Create an array of strings for all n rows
rows = [''] * numRows
current_row = 0
going_down = False

# Traverse the string character by character
for char in s:
rows[current_row] += char
# Change direction if the top or bottom row is reached
if current_row == 0 or current_row == numRows - 1:
going_down = not going_down
current_row += 1 if going_down else -1

# Join all rows to get the final string
return ''.join(rows)

16.54MB, 53ms


C++


#include <string>
#include <vector>

using namespace std;

class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1 || numRows >= s.length()) {
return s;
}

vector<string> rows(min(numRows, int(s.length())));
int currentRow = 0;
bool goingDown = false;

for (char c : s) {
rows[currentRow] += c;
if (currentRow == 0 || currentRow == numRows - 1) {
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}

string result;
for (string row : rows) {
result += row;
}

return result;
}
};

13.49MB, 16ms


Javascript


/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
if (numRows === 1 || numRows >= s.length) {
return s;
}

const rows = Array.from({ length: Math.min(numRows, s.length) }, () => "");
let currentRow = 0;
let goingDown = false;

for (let char of s) {
rows[currentRow] += char;
if (currentRow === 0 || currentRow === numRows - 1) {
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}

return rows.join("");
};

52.92MB, 78ms