ZigZag Conversion
题目中举了二个例子:
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)
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 s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
其原理就是呈左侧的Z型排列字符串,根据行数的不同,呈现大小不同的Z型字符串,如下分别是行数为3和4时的Z型排列:
图一:行数为三
图二:行数为四
解题思路:
根据图一和图二可推算出如下信息:
1.图一中首行P和A字符相隔2 X 3 - 2;
2.图二中首行字符P和I相隔2 X 4 - 2;
可得非斜线字符公式:2*行数 - 2;
3.图一中圆圈标注的字符P位置信息:1 + 2 X 3 - 2 - 2 X 1 = 3;
4.图二中圆圈标注的字符L位置信息:1 + 2 X 4 -2 - 2 X 1 = 5;
为说明斜线计算公式:图二斜线处A位置信息:2 + 2 X 4 -2 - 2 X 2 = 4;
可得斜线字符公式:当前列j+(2*行数-2)-2i(i是行数)不适用于首行
具体代码如下:
class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1)
{
return s;
}
string result = "";
int size = 2 * numRows - 2;
for (int i = 0; i < numRows; ++i)
{
for (int j = i; j < s.size(); j += size)
{
result += s[j];
int tmp = j + size - 2 * i;//for循环中j=i,注意此处
if (i != 0 && i != numRows - 1 && tmp < s.size())//首行除外,首行不包含斜线元素
{
result += s[tmp];
}
}
}
return result;
}
};
性能:
总结:
1.斜线位置计算公式不包含第一行;
2.斜线计算公式中j=i,切记。