25-ZigZag Conversion
2016-04-28 10:21
183 查看
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”.
思路:开始没有清晰的推导规律的思路,先要仔细观察,明确怎么去确定第i行包含S中哪些位置的元素
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”.
思路:开始没有清晰的推导规律的思路,先要仔细观察,明确怎么去确定第i行包含S中哪些位置的元素
class Solution { public: string convert(string s, int nRows) { if(nRows <= 1 || s.length() < 3 || s.length() <= nRows) return s; string s2; int zigSpan = nRows*2 - 2; for (int i = 0; i < nRows; i++) { for (int j = i; j < s.length(); j+=zigSpan) { s2.push_back(s[j]); //先打印间隔相等为zigspan的垂直元素,第i行第一个元素为s[i],下一个s[i+zigspan] //第i行斜线第一个元素的位置nrow-(i+1)+nrow-1=2nrow-2-i,斜线相邻元素相隔zigspan=2nrow-2 //第i行应该是打印,2nrow-2-i+0*zigspan,2nrow-2-i+1*zigspan,2nrow-2-i+2*zigspan,....,2nrow-2-i+n*zigspan //循环中,n=(j-i)*span,起始位置j-i=0 if (i != 0 && i != nRows-1 && zigSpan+j-2*i<s.length()) { s2.push_back(s[zigSpan+j-2*i]); } } } return s2; } };
相关文章推荐
- NumberPicker简单功能用法
- Hierarchical Cluster 层次聚类
- 分词URL
- SQLServer OpenRowSet 导入数据
- 【krpano】krpano xml资源解密(破解)软件说明与下载
- FFMPEG 处理RTMP流媒体的命令大全
- eventfd - create a file descriptor for event notification
- unity 多线程处理
- redis日志出现Can't save in background fork Cannot allocate memory
- Django 模板
- 利用Quart2D作一些简单的图形
- SVN Unable to connect to a repository at URL
- 使用maven创建web项目
- 基于空间金字塔池化的卷积神经网络物体检测
- 三 Python解释器
- Sql Server自动备份数据库,定期删除备份
- bat
- Unity3D学习笔记(三)为地形添加花草树木
- 全球域名解析新增保有量10强:万网排名退至第五
- Swoole介绍-真正的PHP Web开发框架