Leetcode 6 Z 字形變換

2021-09-19 22:59:33 字數 1341 閱讀 3508

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

這道題沒什麼可說的,不需要什麼資料結構與演算法的知識。給定乙個字串,換個花樣輸出。題目中所謂的"z"字形變換,無非就包含兩種操作,直接按題目要求模擬,先豎著往下讀,然後斜上讀,一直將字串讀完為止。

class solution 

stringbuilder sbs = new stringbuilder[numrows];

for (int i = 0; i < numrows; i++)

int index = 0;

while (index < s.length())

// "斜上"讀取,從下往上讀,最後一行和第一行是算在"豎下"讀取中的,所以只存中間numrows - 2行

for (int i = numrows - 2; i > 0 && index < s.length(); i--)

}// 將後面numrows-1行都拼接到第一行

for (int i = 1; i < numrows; i++)

return sbs[0].tostring();}}

LeetCode 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 輸入 s pa...

leetcode 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 示例 1 輸入...

LeetCode 6 Z字形變換

把整個問題拆解為 儲存 取 的兩個過程 通過觀察我發現的是,當numrows為3時,兩列之間的數字的數目為1 當numrows為4時,兩列之間的數字的數目為2,以此類推。那麼,可不可以將每一列都存起來 col 兩列之間的數字也存起來 gap 最後要輸出時再通過遍歷的方式拼接出結果呢?以題目中給的字串...