LeetCode ZigZag Conversion
2016-04-15 11:54
337 查看
The string
this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
return
zigzag变换是这样的操作
![](https://img-blog.csdn.net/20141026161841654?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGppYWJpbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
现在要按行打印,可以观察每一行两个字符的间隔距离,第一行和最后一行的距离都是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;
}
};
"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;
}
};
相关文章推荐
- 字节流
- Linux用户与用户组的添加,查看,删除
- 多个类定义attr属性重复的问题:Attribute "xxx" has already been defined
- mycat 黑匣子
- 简单限速器的实现
- MySQL OnlineDDL
- 尾递归(来自知乎的回答)
- Google 地图 API V3 之 叠加层
- Nginx 实现AJAX跨域请求
- springmvc向页面传值时对list去重
- Coredata的使用方法(简)
- SGU 136 Erasing Edges(计算几何)
- IMAP和POP3有什么区别?
- unity中FPS计算
- @RequestBody的正确使用方法
- Windows-命令窗口-强制关机命令
- HackerRank "Kitty and Katty"
- Javascript 变量作用域 缩写词 及两种定义的区别
- phantomjs 中如何使用xpath
- 细框表格