6 ZigZag Conversion Z 字形變換
Description:
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:
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
題目描述:
將一個給定字符串根據(jù)給定的行數(shù),以從上往下饵蒂、從左到右進行 Z 字形排列篮条。
比如輸入字符串為 "LEETCODEISHIRING" 行數(shù)為 3 時,排列如下:
L C I R
E T O E S I I G
E D H N
之后鼎俘,你的輸出需要從左往右逐行讀取妥粟,產(chǎn)生出一個新的字符串渔彰,比如:"LCIRETOESIIGEDHN"。
請你實現(xiàn)這個將字符串進行指定行數(shù)變換的函數(shù):
string convert(string s, int numRows);
示例 :
示例 1:
輸入: s = "LEETCODEISHIRING", numRows = 3
輸出: "LCIRETOESIIGEDHN"
示例 2:
輸入: s = "LEETCODEISHIRING", numRows = 4
輸出: "LDREOEIIECIHNTSG"
解釋:
L D R
E O E I I
E C I H N
T S G
思路:
- 按 Z字形遍歷字符串, 記錄當前遍歷的行數(shù), 如果遍歷到給定的行數(shù)(0/numRows)就反向
- 寫出 Z字形字符串的下標, 找到下標的規(guī)律, 分成第一行/最后一行和其他行, 按照下標輸出
時間復雜度O(n), 空間復雜度O(n)
代碼:
C++:
class Solution
{
public:
string convert(string s, int numRows)
{
if (numRows == 1) return s;
string result;
int step = 2 * numRows - 2;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j + i < s.size(); j += step)
{
result += s[j + i];
if (i and i != numRows - 1 and j + step - i < s.size()) result += s[j + step - i];
}
}
return result;
}
};
Java:
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++) rows.add(new StringBuilder());
int cur = 0;
boolean next = false;
for (char c : s.toCharArray()) {
rows.get(cur).append(c);
if (cur == 0 || cur == numRows - 1) next = !next;
cur += next ? 1 : -1;
}
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) result.append(row);
return result.toString();
}
}
Python:
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s;
result, step = '', 2 * numRows - 2
for i in range(numRows):
j = 0
while i + j < len(s):
result += s[i + j]
if i and i != numRows - 1 and j + step - i < len(s):
result += s[j + step - i]
j += step
return result