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;
}
};
本文介绍了一种将字符串以Z字形方式排列并按行读取的算法实现。该算法接受一个字符串和行数作为输入参数,返回转换后的字符串。通过实例演示了如何使用这一方法,并提供了详细的代码实现。
1747

被折叠的 条评论
为什么被折叠?



