leetcode No6. ZigZag Conversion
2016-06-15 16:28
197 查看
Question:
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".
即把字符串N字型排列,然后一行一行的输出。
Algorithm:
暴力法,其实可以发现这些排列的规律,利用数学知识求解,但是写这个排列还是费了我一些功夫。
用一个二维数组存储N字排列,一共有nRows行,(s.size()/2)+1列。
然后再遍历二维数组。
Submitted Code:
class Solution { //暴力法 速度太慢 public: string convert(string s, int numRows) { if(numRows==1)return s; vector<vector<char>> array(numRows); string t; for(int i=0;i<numRows;i++) array[i].resize((s.size()/2)+1); int flag=0; //转折点,下或上 int x=0,y=0; //行,列 for(int j=0;j<s.size();j++) { if (x>(numRows-1)) { flag = 1; x = numRows-2; y++; } if (x<0) { flag = 0; x = 1; y--; } array[x][y]=s[j]; if(flag==0) x++; else { x--; y++; } } for(int p=0;p<numRows;p++) for(int q=0;q<((s.size()/2)+1);q++) { if(array[p][q]>='!'&&array[p][q]<='~') t.push_back(array[p][q]); } return t; } };
相关文章推荐
- Atmega16-中断(GCC-AVR)-(ques=1)
- final修饰符,finally,finalize区别
- 响应式编程思想(一)
- Angular的Table 组件
- 本机不安装Oracle客户端,使用PL/SQL Developer连接远程数据库
- 自定义对话框
- HDU 3478 二分图判断
- 图解 windbg设置符号文件路径和使用入门
- 【错误记录】eclipse,android,logcat日志无法打印,真机调试
- 知乎页面出bug了,显示”^Method "question.20946770" (None) is not found.MethodNotFound“
- 本机不安装Oracle客户端,使用PL/SQL Developer连接远程数据库
- 出现( linker command failed with exit code 1)错误总结
- Windows的同步I/O和异步I/O
- C# Async/Await异步函数原理
- HDFS基本Shell命令
- android 编辑框获取软键盘后 将底部控件顶上来解决办法
- 函数式编程
- iOS正则表达式 判断手机号 邮箱 电话 数字 身份证 银行卡
- JS中的call()和apply()方法
- 摩托车继承自行车和机动车