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 0 4 8 12 A P L S I I G 1 3 5 7 9 11 13 Y I R 2 6 10And 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"
.
solution: 正如我们所见,关键之处在于计算(2*nRows -2)的值,姑且命名为zzsize,每一行的红色数字的差值正好为这个值,在中间(nRows-2)行中,我们除了插入这些值外,还需要插入黑色的数字(如图),其下标由前一个数字(index)和当前行数(row)决定,大小应为(index + zzsize - 2 * row)。
class Solution {
public:
string convert(string s, int nRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( nRows <= 0)
return NULL;
else if(nRows == 1)
return s;
string result = "";
int length = s.length();
int zzSize = 2 * nRows - 2;
for(int row = 0; row < nRows; row ++)
{
int index = row;
while(index < length)
{
result = result + s.at(index);
if(row > 0 && row < nRows - 1)
{
int index2 = index + zzSize - 2 * row;
if(index2 < length)
result = result + s.at(index2);
}
index += zzSize;
}
}
return result;
}
};