The string "PAYPALISHIRING"
is written in 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 N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
class Solution {
public:
string convert(string s, int nRows) {
int nLength=s.length()-1;
string s1(s.length(),sizeof(char));
int nIndRow,nIndCol;
int nIndS1=0;
if(nRows==1)
return s;
for(nIndRow=0;nIndRow<=nRows-1;nIndRow++)
{
for(nIndCol=0;nIndCol<=nLength/(2*nRows-2);nIndCol++)
{
if(nIndRow==0)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)];
nIndS1++;
}
if(nIndRow==nRows-1)
{
if(nIndCol!=nLength/(2*nRows-2)||nIndCol*(2*nRows-2)+nRows-1<=nLength)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+nRows-1];
nIndS1++;
}
}
if(nIndRow!=0&&nIndRow!=nRows-1)
{
if(nIndCol==nLength/(2*nRows-2))
{
int nLa=nLength%(2*nRows-2);
if(nLa>=nIndRow)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+nIndRow];
nIndS1++;
}
if(2*nRows-2-nLa<=nIndRow)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+2*(nRows-1)-nIndRow];
nIndS1++;
}
}
else
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+nIndRow];
nIndS1++;
s1[nIndS1]=s[nIndCol*(2*nRows-2)+2*(nRows-1)-nIndRow];
nIndS1++;
}
}
}
}
return s1;
}
};