演算法 Z 字形變換。

2021-10-07 22:14:31 字數 1209 閱讀 5506

將乙個給定字串根據給定的行數,以從上往下、從左到右進行 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);
輸入: s = "leetcodeishiring", numrows = 3

輸出: "lciretoesiigedhn"

輸入: s = "leetcodeishiring", numrows = 4

輸出: "ldreoeiiecihntsg"

解釋:l       d       r

e   o e     i  i

e c    i  h   n

t       s       g

通過從左向右迭代字串,我們可以輕鬆地確定字元位於 z 字形圖案中的哪一行。

我們可以使用 min(numrows,len(s)) 個列表來表示 z 字形圖案中的非空行。

從左到右迭代 s,將每個字元新增到合適的行。可以使用當前行和當前方向這兩個變數對合適的行進行跟蹤。

只有當我們向上移動到最上面的行或向下移動到最下面的行時,當前方向才會發生改變。

class solution 

stringbuilder ret = new stringbuilder();

return ret.tostring();

}}

按照與逐行讀取 z 字形圖案相同的順序訪問字串。

首先訪問 行 0 中的所有字元,接著訪問 行 1,然後 行 2,依此類推...

對於所有整數 k,

class solution 

}return ret.tostring();

}}

演算法 Z字形變換

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

Z字形變換

題目 將字串 paypalishiring 以z字形排列成給定的行數 p a h n a p l s i i g y i r 之後從左往右,逐行讀取字元 pahnaplsiigyir 思路 通過從左向右迭代字串,我們可以輕鬆地確定字元位於 z 字形圖案中的哪一行。演算法 我們可以使用 min num...

Z 字形變換

將乙個給定字串根據給定的行數,以從上往下 從左到右進行 z 字形排列。輸入 s leetcodeishiring numrows 4 輸出 ldreoeiiecihntsg l d r e o e i i e c i h n t s g 注釋思路 class solution 有了列數和行數,總個數...