ZigZag Conversion
The string is "PAYPALISHIRING" written with 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 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" .
Create the NRows array and set S in the order of 0,1,2,..., nrows-2,nrows-1,nrows-2,..., 2,1,0.
Each character in S is loaded into an array.
Then output the 0~nrows-1 array in turn.
classSolution { Public: stringConvertstringSintnRows) { if(s = ="") return ""; if(NRows = =1) returns; Vector<vector<Char> >V (nRows); intTag =1;//1-increase;-1 Decrease intIND =-1; for(inti =0; I < s.size (); i + +) { if(Tag = =1) Ind++; ElseIND--; V[ind].push_back (S[i]); if(Ind = =0) Tag=1; Else if(Ind = = nrows-1)//nRows! = 1Tag =-1; } stringret; for(inti =0; i < nRows; i + +) { for(intj =0; J < V[i].size (); J + +) ret+=V[i][j]; } returnret; }};
"Leetcode" ZigZag Conversion