LeetCode_ZigZag Conversion,leetcode_zigzag

來源:互聯網
上載者:User

LeetCode_ZigZag Conversion,leetcode_zigzag
一.題目ZigZag Conversion  Total Accepted: 31399 Total Submissions: 140315My Submissions

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   NA P L S I I GY   I   R
And then read line by line:  "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return  "PAHNAPLSIIGYIR".Show TagsHave you met this question in a real interview?  Yes No

Discuss












二.解題技巧    這道題是就是原來的字串的元素與鋸齒化後的字串的元素之間的關係,我們可以舉個例子來說明,假設原來的字串的每一個字元的下標為0,1,2,3,..., 12分別進行行數為3,4,5行的鋸齒化後,得到的鋸齒化形狀如下:

    定義將原來的字串按照nRows行進行鋸齒化,定義 Step= 2 * nRows - 2; 從上面的例子可以看出,對於第i行,有下面兩種情況:
1.對於第0行和第(nRows - 1)行,每一行的元素為i, i+Step, i+2*Step,...;2.對於其他的行來說,每一行的元素為i, Step - i, i + Step, 2*Step - i,...。
    得到這些映射關係之後,將上面得到鋸齒化矩陣進行按行展開,放入到新的字串中就得到滿足要求的新字串了。





三.實現代碼

class Solution {public:    string convert(string s, int nRows)    {        const int Size = s.size();        if ((Size <= nRows) || (nRows == 1))        {            return s;        }        const int Step = 2 * nRows - 2;        string Result;        for (int RowIndex = 0; RowIndex < nRows; RowIndex++)        {            int Index = RowIndex;            if ((RowIndex == 0) || (RowIndex == (nRows - 1)))            {                while (Index < Size)                {                    Result.push_back(s[Index]);                    Index = Index + Step;                }                continue;            }            int SecondIndex = Step - Index;            while ((Index < Size) || (SecondIndex < Size))            {                if (Index < Size)                {                    Result.push_back(s[Index]);                    Index = Index + Step;                }                if (SecondIndex < Size)                {                    Result.push_back(s[SecondIndex]);                    SecondIndex = SecondIndex + Step;                }            }        }        return Result;    }};




四.體會    這道題主要是尋找原來是字串的元素座標與鋸齒化後的字串的座標關係,如果將原始字串的元素座標看作是一組已經排好序的數組的話,我們要做的就是如何將這個數組按照一定規律進行亂序,主要是通過幾個例子來推出通用的映射關係,然後根據這些映射關係進行編程即可。畫圖對於解決演算法題目還是十分有效。


著作權,歡迎轉載,轉載請註明出處,謝謝






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.