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 N A P L S I I G Y I RAnd 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 Tags Have you met this question in a real interview? Yes No
Discuss
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; } };