LeetCode #6 ZigZag Conversion (E)
2015-10-01 23:51
246 查看
[Problem]
The string
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
[Analysis]
这题比较简单,大概有两类思路:一是找到规律按一定的间隔直接将字符存入buffer,二是分开每行分别建立字符串最后将所有字符串连接起来。前者规律要稍微复杂一点,但内存方面稍微优化。一开始我采用的是将例子写在纸上找规律的暴力方法,只要将规律列清楚,一样可以求解。
[Solution]
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".
[Analysis]
这题比较简单,大概有两类思路:一是找到规律按一定的间隔直接将字符存入buffer,二是分开每行分别建立字符串最后将所有字符串连接起来。前者规律要稍微复杂一点,但内存方面稍微优化。一开始我采用的是将例子写在纸上找规律的暴力方法,只要将规律列清楚,一样可以求解。
[Solution]
public class Solution { public String convert(String s, int nRows) { if (s.length() <= nRows || nRows == 1) { return s; } StringBuffer buf = new StringBuffer(""); for (int i = 0; i < nRows; i++) { int interval1 = (nRows - i - 1) * 2; int interval2 = i * 2; if (interval2 == 0 || interval1 == interval2) { for (int j = i; j < s.length(); j += interval1) { buf.append(s.charAt(j)); } } else if (interval1 == 0) { for (int j = i; j < s.length(); j += interval2) { buf.append(s.charAt(j)); } } else { buf.append(s.charAt(i)); for (int j = i + interval1; j < s.length(); j += interval1) { buf.append(s.charAt(j)); j += interval2; if (j < s.length()) { buf.append(s.charAt(j)); } } } } return buf.toString(); } }
相关文章推荐
- linux内存管理之kmalloc
- 003 All Primitives In Java
- LeetCode_LinkedList_Easy
- debian连接网络
- komodo,mysql workBeach
- iOS多线程
- Heap:Expedition(POJ 2431)
- 怎么成为一个优秀的程序员,而不是一个优秀的码农?
- ICMP
- linux 自己用到的一些命令,留下备忘。
- Caffe中HDF5Data例子
- iOS KVO和KVC及广播
- git rebase -i
- python基础5之错误处理
- MySQL创建用户与授权方法
- Spring+Quartz 从数据库中获取定时任务和定时时间,动态实现对定时任务的增删改查
- ubuntu firefox install flash
- iOS线程安全
- Odoo9发行说明
- 使用命令行安装安卓应用