您的位置:首页 > 其它

(算法分析Week10)ZigZag Conversion[Medium]

2017-11-09 13:31 405 查看

6.ZigZag Conversion[Medium]

题目来源

Description

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”.

Solution

zigzag是锯齿型的意思,一开始没明白题目要干什么,但是仔细研究样例应该能理解。举几个例子:

nRows为2时,字符串坐标变成zigzag的走法就是:
0 2 4 6
1 3 5 7

nRows取3时:
0     4     8
1  3   5  7  9

nRows取4时:
0      6        12
1   5   7      11 13
2 4      8  10     14
3          9         15


比较直观的想法是用一个字符串数组string[rows]来存储每一行,用一个delta表示正向还是反向,即上图中从第一行到最后一行还是最后一行到第一行。最后把字符串数组拼接起来就可以了。

不过可以尝试找一下规律,发现所有行的重复周期都是 (2 * nRows - 2)。

对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 (2 * nRows - 2 - 2 * i)

Complexity analysis

O(n²)

Code

class Solution {
public:
string convert(string s, int nRows) {
if (nRows <= 1 || s.length() == 0)
return s;

string res = "";
int len = s.length();
for (int i = 0; i < len && i < nRows; ++i)
{
int indx = i;
res += s[indx];

for (int k = 1; indx < len; ++k)
{

if (i == 0 || i == nRows - 1)
{
indx += 2 * nRows - 2;
}

else
{
if (k % 2 == 1)
indx += 2 * (nRows - 1 - i);
else indx += 2 * i;
}

if (indx < len)
{
res += s[indx];
}
}
}
return res;
}
};


Result

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: