[leetcode 6] ZigZag Conversion
2015-12-11 08:36
417 查看
Question:
The string
of rows like 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
分析:
上图例子中下标顺序为:
可以看出一个规律就是第0行和第nRows-1行的下标间隔是一样的,为interval = 2*nRows-2;中间行的下标是跳跃的,依次为 interval - 2*i;2*i;interval - 2*i;2*i。。。
所以返回的字符串为nRows个字符串串联的结果;
代码如下:
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".
分析:
上图例子中下标顺序为:
0 | 4 | 8 | 12 | |||
1 | 3 | 5 | 7 | 9 | 11 | 13 |
2 | 6 | 10 |
所以返回的字符串为nRows个字符串串联的结果;
代码如下:
class Solution { public: string convert(string s, int numRows) { string result = ""; int interval = 2 * numRows - 2; int len = s.size(); if(len <= numRows || numRows == 1) return s; for(int i = 0; i < numRows; ++i){ int pos = i; if(i == 0 || i == numRows-1){ while(pos < len){ result += s[pos]; pos += interval; } } else{ int b = 2 * i; while(pos < len){ result += s[pos]; b = interval - b; pos += b; } } } return result; } };
相关文章推荐
- Java中关于HashMap的使用和遍历
- “知原理”题目2
- IE下判断IE版本的语句...[if lte IE 6]……[endif]
- 第十周:二叉树的基本运算及其实现
- 第十四周项目3是否二叉排序树?
- 第14周项目3-是否二叉排序树?
- 音频实时传输和播放AMR硬编码与硬解码
- 关于阿里云上Linux装jdk与apache
- 第十五周--项目4算法验证直接插入排序
- 为什么OLED对LCD是颠覆性技术,听听摄影专家怎么说
- 第9周项目1猴子选大王问题
- 【ASP】OLEDB方式连接各类数据库(sql,access,excel,txt)
- “知原理”题目1
- vsftpd出现“Response: 500 OOPS: cannot change directory”解决方法(转载)
- 第十二周项目4-利用遍历思想求解图问题(4)
- 解决IllegalStateException: Can not perform this action after onSaveInstanceState
- JSON使用ConstructorHanding反序列化非公共构造函数
- Android ListView 单条刷新方法实践及原理解析
- Java Swing JScrollPane 设置滚动量
- 第十五周项目1--验证算法