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" .
A simple simulation problem.
Directly on the code: (Runtime: Ms)
classSolution { Public: stringConvertstringSintnRows) { if(NRows = =1) returns; stringres =s; intRound =2*nrows-2; intLen =res.length (); intpos =0; for(inti =0; i < nRows; ++i) {intK =0; intCur = k*round+i; while(true) {cur= K*round +i; if(cur >=len) Break; Res[pos++] =S[cur]; if(I! =0&& I! = nRows-1) {cur= (k +1) *round-i; if(cur >=len) Break; Res[pos++] =S[cur]; } ++K; } } returnRes; }};
Leetcode Problem 6 ZigZag Conversion