一. 题目描述
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"
.
二. 题目分析
这道题是就是原来的字符串的元素与锯齿化后的字符串的元素之间的关系,我们可以举个例子来说明,假设原来的字符串的每一个字符的下标为0,1,2,3,…, 12分别进行行数为3,4,5行的锯齿化。
定义将原来的字符串按照nRows行进行锯齿化,定义 Step= 2 * nRows - 2; 从上面的例子可以看出,对于第i行,有下面两种情况:
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) {
if (nRows <= 1) return s;
string result = "";
int step = 2 * nRows - 2;
for (int i = 0; i < nRows; ++i)
{
for (int j = i; j < s.size(); j += step)
{
result = result + s[j];
int midIndex = (j - i) + step - i;
if (i != 0 && i != nRows - 1 && midIndex < s.size())
result = result + s[midIndex];
}
}
return result;
}
};
四. 小结
这道题主要是寻找原来是字符串的元素坐标与锯齿化后的字符串的坐标关系。