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