Leetcode Note: ZigZag Conversion
I. Description
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)Shocould return"PAHNAPLSIIGYIR".
Ii. Question Analysis
This question is the relationship between the elements of the original string and the elements of the Sawtooth string. We can give an example to illustrate, assume that the subscript of each character in the original string is 0, 1, 2, 3 ,..., 12. The number of rows is 3, 4, and 5, respectively.
The definition of the original string according to the nRows line for sawtooth, the definition of Step = 2 * nRows-2; from the example above, we can see that for line I, there are two situations:
1. For rows 0th and (nRows-1), the elements of each row are I, I + Step, I + 2 * Step ,...;
2. For other rows, the elements of each row are I, Step-I, I + Step, 2 * Step-I ,....
Iii. instance code
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; }};
Iv. Summary
This topic is mainly used to find the coordinate relationship between the element coordinates of the original string and the character string after the Sawtooth.