I. Title Description
The string "Paypalishiring" is written with a zigzag pattern on a given number of rows like this: (You could want to display T His pattern in a fixed font for better legibility)
P A H NII GY I R
And then read on line: "PAHNAPLSIIGYIR"
Write the code that would take a string and make this conversion given a number of rows:
String convert (string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
Two. Topic analysis
This question is the relationship between the elements of the original string and the elements of the jagged string, and we can give an example to illustrate that assuming the original string of each character's subscript is 0,1,2,3, ..., 12 respectively, the number of rows for the 3,4,5 line is jagged.
Defines the original string to be aliased according to the NRows line, defining step= 2 * nRows-2; As can be seen from the above example, for line I, there are two situations:
1. For lines No. 0 and (nRows-1), the elements of each line are I, I+step, I+2*step,... ;
2. For other lines, the element for each row is I, step-i, i + Step, 2*step-i,...。
Three. Instance code
class Solution{public:string Convert(string s, int nRows){Const INTSize= S.size(); If(Size <= nRows)||(nRows = = 1)) {return s; } const INTStep= 2 * NROWS-2; StringResult; For(int RowIndex = 0; RowIndex < nRows; RowIndex+ +){intIndex=RowIndex; If((RowIndex = = 0)||(RowIndex = = (nRows -1))) {While(Index < Size){Result. push_back(s[Index]);Index=Index+Step; } continue; } intSecondindex=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; }}} returnResult; }};
Four. Summary
This problem is mainly to find the original string of the element coordinates and the jagged string after the coordinate relationship.
Leetcode notes: ZigZag Conversion