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)
{
string res;
size_t len = s.length();
if (0 == len || nRows < 1) return res;
if (1 == nRows || 1 == len) return s;
int tmp = len/(2*nRows - 2);
int range = len%(2*nRows - 2) == 0 ? tmp-1 : tmp;
for (int i = 0; i < nRows; i++)
{
for (int j = 0; j <= range; j++)
{
if (0 == i && j*2*(nRows - 1) < len)
res.push_back(s[j*2*(nRows - 1)]);
else if (i + 1 == nRows && (j*2 + 1)*(nRows - 1) < len)
res.push_back(s[(j*2 + 1)*(nRows - 1)]);
else
{
if (j*2*(nRows - 1) + i < len)
res.push_back(s[j*2*(nRows - 1) + i]);
if ((j*2 + 1)*(nRows - 1) + nRows - 1 - i < len)
res.push_back(s[(j*2 + 1)*(nRows - 1) + nRows - 1 - i]);
}
}
}
return res;
}
};