6 Z 字形變換

2021-10-05 06:41:16 字數 1522 閱讀 2754

將乙個給定字串根據給定的行數,以從上往下、從左到右進行 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

class solution:

def convert(self, s: str, numrows: int) -> str:

n = len(s)

if n <= numrows or numrows == 1:

return s

ans = ''

step1 = numrows * 2 - 2

step2 = 0

for i in range(numrows):

index = i

ans += s[index]

while index < n:

index += step1

if step1 != 0 and index < n:

ans += s[index]

index += step2

if step2 != 0 and index < n:

ans += s[index]

step1 -= 2

step2 += 2

return ans

python實現**

def convert(s: str, numrows: int) -> str:

if numrows == 1 or numrows >= len(s):

return s

r = [''] * numrows

j = 0

k = 1

for i in s:

r[j] += i

j += k

if j == 0 or j == numrows - 1:

k = -k

return "".join(r)

6 Z字形變換

一 題目 將字串 paypalishiring 以z字形排列成給定的行數 p a h n a p l s i i g y i r之後從左往右,逐行讀取字元 pahnaplsiigyir 實現乙個將字串進行指定行數變換的函式 string convert string s,int numrows 示例...

6 Z字形變換

將字串 paypalishiring 以z字形排列成給定的行數 p a h n a p l s i i g y i r 之後從左往右,逐行讀取字元 pahnaplsiigyir 示例1 輸入 s paypalishiring numrows 3 輸出 pahnaplsiigyir 示例 2 輸入 s...

6 Z 字形變換

將乙個給定字串根據給定的行數,以從上往下 從左到右進行 z 字形排列。比如輸入字串為 leetcodeishiring 行數為 3 時,排列如下 l c i r e t o e s i i g e d h n之後,你的輸出需要從左往右逐行讀取,產生出乙個新的字串,比如 lciretoesiigedh...