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"
//1:当nRows不大于1的时候,直接返回原来字符串;2:考虑i == 0 和i == nRows - 1两种情况; 3:当i介于两者之间的时候氛围两种情况:k += 2 * (nRows - 1 - i) 以及 k += 2 * i
string convert(string s, int nRows)
{
if(nRows <= 1)
return s;
string result = "";
int length = (int)s.size();
for(int i = 0; i < nRows; i++)
{
if(i == 0 || i == nRows - 1)
{
int k = i;
while( k < length)
{
result.push_back(s[k]);
k += 2 * (nRows - 1);
}
}
else
{
int k = i;
bool flag = false;
while(k < length)
{
result.push_back(s[k]);
if(flag == false)
{
k += 2 *(nRows - 1 - i);
flag = true;
}
else
{
k += 2 * i;
flag = false;
}
}
}
}
return result;
}