LeetCode——ZigZag Conversion
2015-07-10 08:13
267 查看
The string
number 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
字符串的弯曲转换。
要做的首先就是发现每一行的规律,能够发现,每一行有2 * nRows - 2个字符。把结果的列先增加到新的字符串中。再增加行。
"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".
字符串的弯曲转换。
要做的首先就是发现每一行的规律,能够发现,每一行有2 * nRows - 2个字符。把结果的列先增加到新的字符串中。再增加行。
public String convert(String s, int nRows) { if(nRows <= 1) return s; StringBuffer buf = new StringBuffer(); int period = 2 * nRows - 2; for(int i=0;i<nRows;i++){ for(int j=i;j<s.length();j+=period){ buf.append(s.charAt(j)); if(i !=0 && i != nRows - 1 && j+period - 2*i <s.length()) buf.append(s.charAt(j+period - 2*i)); } } return buf.toString(); }
相关文章推荐
- ADT in python DEMO
- 【转】创业生存指南
- Win10预览版10166快速版更新:修复Bug和性能改进
- oc中一些概念和关键字
- CocoaPods pod install/pod update更新慢的问题
- Java 兑换ObjectC代码
- 交换机接口类型
- 墓志铭:非常了得其实早已死了
- UML各种关系
- Win10预览版10166更新了什么 Win10预览版10166更新汇总
- 类与对象
- 【剑指Offer学习】【面试题53:正则表达式匹配】
- 在SQL Server 2014里,如何用资源调控器压制你的存储?
- Android新版NDK环境配置(免Cygwin)
- 【翻译自mos文章】当指定asm disk 为FRA时,11.2.0.3的dbua hang住
- n每个计数的概率和发生骰子--动态规划
- PHP情人:p十几天来学习hp第一天
- Spark:Yarn-cluster和Yarn-client区别与联系
- java基础——static 关键字小节
- 创业中,感受书本和现实的距离——北漂18年(16)