[Leetcode] ZigZag Conversion (Java)
2013-12-26 12:52
666 查看
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
开始写成
一直报错Memory Limit Exceeded
后来改成
就没事了
难道StringBuilder比好多String占的memory还大么。。去看看源码好了。。
"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".
开始写成
public class ZigZagConversion { public String convert(String s, int nRows) { if(s.length()<2 || nRows<=1) return s; StringBuilder sb = new StringBuilder(); for(int i=0;i<nRows;i++) { int temp = i; while(temp<s.length()) { sb.append(s.charAt(temp)); if(i!=0&&i!=nRows-1&&temp+2*(nRows-i-1)<s.length()){ sb.append(s.charAt(temp+2*(nRows-i-1))); } temp +=2*(nRows-1); } } return sb.toString(); } public static void main(String[] args) { System.out.println(new ZigZagConversion().convert("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 6)); } }
一直报错Memory Limit Exceeded
后来改成
public class ZigZagConversion { public String convert(String s, int nRows) { if(s.length()<2 || nRows<=1) return s; String ss = ""; for(int i=0;i<nRows;i++) { int temp = i; while(temp<s.length()) { ss+=s.charAt(temp); if(i!=0&&i!=nRows-1&&temp+2*(nRows-i-1)<s.length()){ ss+=s.charAt(temp+2*(nRows-i-1)); } temp +=2*(nRows-1); } } return ss; } public static void main(String[] args) { System.out.println(new ZigZagConversion().convert("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 6)); } }
就没事了
难道StringBuilder比好多String占的memory还大么。。去看看源码好了。。
相关文章推荐
- jdk安装
- jsp脚本提取struts2中action的属性值
- Java中获取路径的各种方法
- JAVA迅速解决图片变红、变黑、压缩平滑问题
- java反射详解
- 解决myeclipse引用单独的js外部文件时中文编码问题(解决的是js文件本身编码问题)
- 黑马程序员_Java基础加强之JDK1.5的新特性
- java--javadoc--Javadoc转换chm帮助文档的四种方法总结
- java---javadoc---Eclipse中javadoc的使用以及中文乱码的解决
- java冒泡排序
- Java中遍历文件夹的2种方法
- JAVA 考试准备笔记 3
- Eclipse下搭建Hadoop开发环境,并运行第一个实例
- eclipse快捷键汇总
- 利用java实现windows关机
- win7下hadoop编程eclipse的配置
- 如何为SpringSource Tool Suite 安装主题Eclipse Color Themes
- Java Json 序列化与反序列化
- Java时间处理之二(xx天前、xx年前)
- java中获取服务器的IP和端口