您的位置:首页 > 其它

6. ZigZag Conversion

2017-03-28 00:23 169 查看
题目:
The string "PAYPALISHIRING" iswritten in a zigzag pattern on a given number of rows like this: (you may wantto 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 readline by line: "PAHNAPLSIIGYIR"

Write the code that will take a stringand 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 numRows) {

}
};


方法一:LeetCode上本题的难度是中等,但是我自认为本题偏难,在短时间内完成不了,主要是找规律。

/*n=numRows
Δ=2n-2    1                           2n-1                         4n-3
Δ=        2                     2n-2  2n                    4n-4   4n-2
Δ=        3               2n-3        2n+1              4n-5       .
Δ=        .           .               .               .            .
Δ=        .       n+2                 .           3n               .
Δ=        n-1 n+1                     3n-3    3n-1                 5n-5
Δ=2n-2    n                           3n-2                         5n-4
*/


找到的规律:第i行元素两两相隔分别为Step1=(总行数-i-1)*2,step2=i*2;

第0行:step1=2n-2,step2=0;

第1行:step1=2n-4,step2=2;

第2行:step1=2n-6,step2=4;

……

……

第n-2行:step1=2,step2=2n-4;

第n-1行:step1=0,step2=2n-2;

程序如下

class Solution1 {
public:
string convert(string s, int numRows) {
string result = "";
if (numRows == 1)
return s;
int step1, step2;
int len = s.size();
for (int i = 0; i<numRows; ++i){
step1 = (numRows - i - 1) * 2;
step2 = (i)* 2;
int pos = i;
if (pos<len)
result += s.at(pos);
while (1){
pos += step1;
if (pos >= len)
break;
if (step1)
result += s.at(pos);
pos += step2;
if (pos >= len)
break;
if (step2)
result += s.at(pos);
}
}
return result;
}
};
方法二:
关键是要会如何计算各个字符的位置,方法一是利用相对间隔,法二是将法一改进了一下,利用了相对间隔求出元素所在的位置。

我们只对一个Z图作分析
/*
1                           2n-1
2                     2n-2  2n
3               2n-3        2n+1
.           .               .               .            .
.       n+2                 .
n-1 n+1                     3n-3
n                           3n-2

*/


1、 Z字形行数为nRows,那么最左最右边间隔字符zigSpan = nRows*2-2;

2 、第一行和最尾一行只有两个元素,所以存储的字符为间隔为zigSpan的字符

3 、中间行是三个元素,左右边的元素位置好计算为:j+=zigSpan,我们主要考虑中间元素的位置,经过推倒为:zigSpan + j-2*i,其中i为行,j为每行中的第几个数,计数全部从0开始;

程序如下:

class Solution {
public:
string convert(string s, int nRows)
{
if (nRows <= 1 || s.length() < 3 || s.length() <= nRows) return s;
string result;
int zigSpan = nRows * 2 - 2;
for (int i = 0; i < nRows; i++)
{
for (int j = i; j < s.length(); j += zigSpan)
{
result.push_back(s[j]);
//利用推导公式zigSpan+j-2i
if (i != 0 && i != nRows - 1 && zigSpan + j - 2 * i<s.length())
{
result.push_back(s[zigSpan + j - 2 * i]);
}
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode ZigZag