6. ZigZag Conversion
2016-07-19 21:29
260 查看
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”.
一道好烦的easy,首先题意就难懂233333,做法也很简单,就每一个字符新的位置放入一个重载的队列中,最后生成新的string。
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”.
一道好烦的easy,首先题意就难懂233333,做法也很简单,就每一个字符新的位置放入一个重载的队列中,最后生成新的string。
class Solution { struct num { char c; int a1, a2; bool operator < (const num& n) const{ return a1 > n.a1 || (a1 == n.a1 && a2 > n.a2); } }; public: string convert(string s, int numRows) { if(numRows == 1) return s; priority_queue<num>pp; int len = s.length(); for(int i = 0; i < numRows; ++ i) { num x; x.c = s[i]; x.a1 = i + 1; x.a2 = 1; pp.push(x); } int nowa = numRows, nowb = 1; int i = numRows; while(i < len) { for(int j = 1; j <= numRows - 2 && i < len; ++i, ++j) { nowa--;nowb++; num x; x.c = s[i]; x.a1 = nowa; x.a2 = nowb; pp.push(x); } nowa--;nowb++; if(i >= len) break; for(int j = 1; j <= numRows && i < len; ++i, ++j) { num x; x.c = s[i]; x.a1 = nowa; x.a2 = nowb; pp.push(x); nowa++; } nowa--; } string news = ""; for(int k = 0; k < len; ++k) { num newc = pp.top(); news.push_back(newc.c); pp.pop(); } return news; } };
相关文章推荐
- Delphi窗体置顶及失去焦点后取得焦点
- 大数据Spark “蘑菇云”行动前传第2课:Scala零基础实战入门的第一堂课及如何成为Scala高手
- Power of Two
- android--checkbox(内部监听器)
- UVA 1587 Box
- servlet+jdbc+sql分页
- python初级项目课(一)
- ANDROID 中常用的第三方框架
- 大型网站架构演化发展历程
- 一笔画问题
- 使用WinSCP完成Windows与Linux之间的文件传输
- python3的模块import操作
- EM算法的一些整理
- Fillder的autoresponder功能
- android判断当前系统版本的等级
- Counting Leaves
- 工具箱
- MyEclipse 创建 WebProject 项目
- 开发中遇到的JSON字符串转换的小问题
- Lowest Common Ancestor of a Binary Search Tree