LeetCode演算法題6:Z 字形變換解析
阿新 • • 發佈:2018-11-21
將一個給定字串根據給定的行數,以從上往下、從左到右進行 Z 字形排列。
比如輸入字串為 “LEETCODEISHIRING” 行數為 3 時,排列如下:
L C I R
E T O E S I I G
E D H N
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:“LCIRETOESIIGEDHN”。
請你實現這個將字串進行指定行數變換的函式:
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
這個題就是一個找規律的題,每一行的字母索引都是按步可找的。所以找一下規律先,其實看示例2,第一行就是每個元素之間都差2*numRows-2,最後一行也是這樣,中間的兩行一部分元素是這樣,還有一部分元素與行數有關。所以程式就可以直接編寫了:
C++原始碼:
class Solution {
public:
string convert (string s, int numRows) {
if (numRows == 1) return s;
string str;
int n = s.length();
int step = 2 * numRows - 2;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j + i < n; j += step)
{
str += s[j + i] ;
if (i != 0 && i != numRows - 1 && j + step - i < n)
str += s[j + step - i];
}
}
return str;
}
};
python3原始碼:
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows==1:
return s
ns = ""
n = len(s)
step = 2 * numRows - 2
for i in range(numRows):
for j in range(i, n, step):
ns += s[j]
if i!=0 and i!=numRows-1 and j+step-2*i<n:
ns += s[j+step-2*i]
return ns