LeetCode ZigZag Conversion
2015-10-14 22:27
387 查看
题目:
分析:
题目要求对一个字符串按给定的行数呈‘Z’形排列,
仔细研究发现,每2*numRows - 2个字符是一组,即
是一组,其实本题考查的是对mod的运用,看出这一点就不难找出规律了
代码:
[code]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".
分析:
题目要求对一个字符串按给定的行数呈‘Z’形排列,
[code]0 6 1 5 7 2 4 8 3 9
仔细研究发现,每2*numRows - 2个字符是一组,即
[code]0 1 5 2 4 3
是一组,其实本题考查的是对mod的运用,看出这一点就不难找出规律了
代码:
[code] public String convert(String s, int numRows) { StringBuilder res = new StringBuilder(); int len = s.length(); if(len == 0 || numRows == 1) return s; int group = 2 * numRows - 2; int col ; if(len % group <= numRows - 1) col = (len / group) * (numRows - 1) + 1; else col = (len / group) * (numRows - 1) + len % group + 1 - numRows; char [][] tmp = new char[numRows][col]; for(int i = 0;i < numRows;i++) for(int j = 0;j<col;j++) tmp[i][j] = '/'; for(int i = 0;i < len;i++) { int tmp_row,tmp_col; if(i % group <= numRows - 1) { tmp_row = i % group; tmp_col = (i / group) * (numRows - 1); } else { tmp_row = group - i % group; tmp_col = ((i % group) - numRows + 1) + (i / group) * (numRows - 1); } tmp[tmp_row][tmp_col] = s.charAt(i); } for(int i = 0 ;i < numRows;i++) for(int j = 0;j < col;j++) if(tmp[i][j] != '/') res.append(tmp[i][j]); return res.toString(); }
相关文章推荐
- 常见 wifi热点的linux 驱动
- 链接详解--共享库命名
- iOS8上放大缩小的动画
- Windows服务编写原理及探讨【4】
- 使用 PGStrom 2 (GPU JOIN, BulkScan, GpuPreAgg, ...)
- 黑马程序员一一Java基础语法(四)
- Android串口例子
- WebRTC VideoEngine超详细教程(三)——集成X264编码和ffmpeg解码
- linux 显示一个文本的某几行
- webform之session传值(临时数据的存储)与扩展属性 --(购物车练习)
- iOS新上线注意事项
- git使用ssh密钥
- 试用 PGStrom
- Windows服务编写原理及探讨【3】
- MySQL笔记
- 黑马程序员-hashCode()的作用
- springMVC的HandlerInterceptor拦截器
- 代码: 两列图片瀑布流(一次后台取数据,图片懒加载。下拉后分批显示图片。图片高度未知,当图片onload后才显示容器)
- PHP zendstudio framework2配置过程
- useful function & operator & custom operator for Row and Array Comparisons