力扣 Z字形變換

2021-10-11 22:54:45 字數 1188 閱讀 4269

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

public:

string convert(string s, int numrows){

if(numrows==1) return s;//當乙個的時候,就會直接返回

int cnt=min(numrows,(int)s.size());//行數和字元數之間的關係,需要找最小

vectorrows(cnt);//這裡就是用它儲存每一行的數字

bool f=0;//邊界的標記,仔細的話,會發現行數在來回滾動。最開始遞增,然後遞減。

string res;//最終的答案

int currows=0;//當前行的變數

for(int i=0;i蟹蟹各位觀眾老爺

6 Z 字形變換 力扣

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

力扣LeetCode 6 Z 字形變換

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

力扣日記 006 Z字形變換

將乙個給定字串根據給定的行數,以從上往下 從左到右進行 z 字形排列。比如輸入字串為 leetcodeishiring 行數為 3 時,排列如下 之後,你的輸出需要從左往右逐行讀取,產生出乙個新的字串,比如 lciretoesiigedhn 超粗略方法,第一次修改,沒考慮空字串情況 第二次,沒考率字...