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 R
And 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.对于第0行和第(nRows - 1)行,每一行的元素为i, i+Step, i+2*Step,...;2.对于其他的行来说,每一行的元素为i, Step - i, i + Step, 2*Step - i,...。
class Solution {
public:
string convert(string s, int nRows)
{
const int Size = s.size();
if ((Size <= nRows) || (nRows == 1))
{
return s;
}
const int Step = 2 * nRows - 2;
string Result;
for (int RowIndex = 0; RowIndex < nRows; RowIndex++)
{
int Index = RowIndex;
if ((RowIndex == 0) || (RowIndex == (nRows - 1)))
{
while (Index < Size)
{
Result.push_back(s[Index]);
Index = Index + Step;
}
continue;
}
int SecondIndex = Step - Index;
while ((Index < Size) || (SecondIndex < Size))
{
if (Index < Size)
{
Result.push_back(s[Index]);
Index = Index + Step;
}
if (SecondIndex < Size)
{
Result.push_back(s[SecondIndex]);
SecondIndex = SecondIndex + Step;
}
}
}
return Result;
}
};
原文:http://blog.csdn.net/sheng_ai/article/details/44325929