【Leetcode】Python實現Z字形變換
阿新 • • 發佈:2018-12-31
Z字形變換
題意解釋:
比如有一個字串 “0123456789ABCDEF”,轉為zigzag
當 n = 2 時:
0 2 4 6 8 A C E
1 3 5 7 9 B D F
當 n = 4 時:
0 6 C
1 5 7 B D
2 4 8 A E
3 9 F
解題思路:
這道題就是看座標的變化。並且需要分塊處理。
n=2時,字串座標變成zigzag的走法就是:
0 2 4 6
1 3 5 7
n=3時的走法是:
0 4 8 1 3 5 7 9 2 6 10
我們發現,除了第一行和最後一行沒有中間形成之字型的數字外,其他都有,而首位兩行中相鄰兩個元素的index之差跟行數是相關的,為 2*nRows - 2, 根據這個特點,我們可以按順序找到所有的黑色元素在元字串的位置,將他們按順序加到新字串裡面。對於紅色元素出現的位置也是有規律的,每個紅色元素的位置為 j + 2*nRows-2 - 2*i, 其中,j為前一個黑色元素的列數,i為當前行數。 比如當n = 4中的那個紅色5,它的位置為 1 + 2*4-2 - 2*1 = 5,為原字串的正確位置。當我們知道所有黑色元素和紅色元素位置的正確演算法,我們就可以一次性的把它們按順序都加到新的字串裡面。
解法一:
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
str_length = len(s)
ans = ""
if numRows <= 1:
return s
for i in range(numRows):
c1 = 2 *numRows - 2*(i+1)
c2 = 2 * i
cnt = i
ans += s[cnt]
while cnt < str_length:
if c1 != 0:
cnt += c1
if cnt < str_length:
ans += s[cnt]
if c2 != 0:
cnt += c2
if cnt < str_length:
ans += s[cnt]
return ans
解法二:
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
str_length = len(s)
node_length = 2*numRows - 2 # 兩列之間的差
result = ""
if str_length == 0 or numRows == 0 or numRows == 1:
return s
for i in range(numRows): # 從第一行遍歷到最後一行
for j in range(i, str_length, node_length):
result += s[j] # 第一行和最後一行 還有普通行的整列數字
if i != 0 and i != numRows-1 and j - 2*i + node_length < str_length:
result += s[j-2*i+node_length] # 單列行的數字
return result