您的位置:首页 > 其它

LeetCode ZigZag Conversion

2016-04-15 11:54 337 查看
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"
.

zigzag变换是这样的操作



现在要按行打印,可以观察每一行两个字符的间隔距离,第一行和最后一行的距离都是2rows-2,其他行不同,从下往上的(奇数位)的间隔是2rows-2-2i,从下往上的间隔是2i.

class Solution {
public:
string convert(string s, int numRows) {
//这个题主要在于找规律,可以观察到第一行和最后一个的间隔都是2rows-2,其他行需要考虑两种情况,当第一次找第二位数的时候间隔是2rows-2i-2,但是找第三个数的时候间隔会变小成为2i
if(numRows <= 1) return s;
int pos = 0;
string result;
for(int i = 0;i<numRows;i++)
{
int flag = 0;
for(int j = i;j<s.length();)
{
if(i == 0 || i == numRows-1)
{
result.push_back(s[j]);
pos = 2*numRows-2;
j = j+pos;
}else
{
if(flag == 0)
{
result.push_back(s[j]);
pos = 2*numRows-2*i-2;
j = j+pos;
flag = 1;
}else
{
result.push_back(s[j]);
pos = 2*i;
j = j+pos;
flag = 0;
}
}
//cout<<result<<endl;
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: