Topic:
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"
.
Code:
classSolution { Public: stringConvertstringSintnumrows) { Const intLen =s.size (); if(Len<numrows | | numrows==1)returns; Vector<Char>ret; Const intINTERVAL =2*numrows-2; for(intI=0; i<numrows; ++i) {intInterval =2* (Numrows-i)-2; for(intJ=i; j<len; interval=interval-interval) {Ret.push_back (s[j]); J= (interval==interval| | interval==0) ? j+interval:j+interval; } } return string(Ret.begin (), Ret.end ()); }};
Tips
Find the regularity of the interval size of each row element in the zigzag string s.
"ZigZag Conversion" cpp