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"
.
Ideas:
1, NumRows can calculate how many letters a cycle (for example, the above example is 4 letters a loop)
2, the number of vertical characters is numrows, the number of characters in the slash section is actually numRows-2, each (NumRows * 2-2) Number of a loop
3, each offset increase (numrows * 2-2), then output can be. The only criterion for determining if the position has characters is if it is out of bounds, so easy
The source code is as follows:
#include <iostream>#include<string>#include<vector>using namespacestd;classSolution { Public: stringConvertstringSintnumrows) { if(NumRows = =1)returns; stringstrresult; intIlen =s.size (); intIcellnum = NumRows *2-2; for(inti =0; i < numrows; ++i) {if(i = =0|| i = = NumRows-1) { intj =i; while(J <Ilen) {Strresult+=S[j]; J+=Icellnum; } } Else { intj =i; intK = Icellnum-i; while(J <Ilen) {Strresult+=S[j]; J+=Icellnum; if(K <Ilen) {Strresult+=S[k]; K+=Icellnum; } } } } returnstrresult; }};intMain () {solution A; stringstrresult = A.convert ("paypalishiring",3); printf ("%s\n", Strresult.c_str ()); System ("Pause"); return 0;}
Leetcode [006]: ZigZag Conversion