LeetCode字串 6Z字形變換

2021-10-03 12:58:06 字數 1079 閱讀 3923

題目描述:

將乙個給定字串根據給定的行數,以從上往下、從左到右進行 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字形變換的原因。 將原題目中的排列方式做類似矩陣轉置的操作,這時候整個排列就是類似z字形的變換,例如:

l  e  e

tc o d

ei s h

ir i n

g

所以想辦法通過leetcodeishiring得到轉置之後的矩陣,然後只要先縱向輸出再橫向輸出就可以了。

string convert(string s, int numrows) 

} if (left == 0)

else if (left <= numrows)

else

} for (int j = 0; j < numrows; j++)

for (int i = 0; i < zshapematrix.size(); i++)

return ans;

}

6 Z 字形變換 leetcode

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

6 Z字形轉換

將乙個給定字串根據給定的行數,以從上往下 從左到右進行 z 字形排列。比如輸入字串為 leetcodeishiring 行數為 3 時,排列如下 之後,你的輸出需要從左往右逐行讀取,產生出乙個新的字串,比如 lciretoesiigedhn 請你實現這個將字串進行指定行數變換的函式 string c...

LeetCode題解 6 Z 字形變換

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