Leetcode_38_count-and-say
来源:互联网 发布:小学生信息编程课程 编辑:程序博客网 时间:2024/05/18 01:52
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41257397
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.11
is read off as "two 1s"
or 21
.21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
今天OJ可好几次,提交好几次都出错,最后才发现是自己把题目理解错了,回头想想就觉得好笑。
题目的意思是给定一个整数n,让你求出按照上面规律在执行若干次后所得到的串,其实该算法主要用到递归的思想。
例如n=1时输出“1”,n=2时输出“2”......
我却把题目意思错误地理解为:对于给定的整数n,对该整数n执行N次上述递归操作后得到的串。例如给定2,得到的结果是1112。
当我将给定整数设定为1000时,果断出现内存泄露,想想就觉得可怕。
按照:“对于给定的整数n,对该整数n执行N次上述递归操作后得到的串”的算法描述如下所示:
public class TestCountAndSay {private static String countAndSay;public static void main(String[] args) {countAndSay = countAndSay(12);System.err.println(countAndSay);}public static String countAndSay(int n) {String value = String.valueOf(n);for (int i = 0; i < n; i++) {value = getAllSays(value);}return value; }public static String getAllSays(String value){StringBuffer buffer = new StringBuffer();int len = value.length();int pos = 0;int max = 1;for (int i = 1; i <=len;i++ ) {if(i<len && (int)value.charAt(i) == (int)value.charAt(pos)){max++;continue;}else{buffer.append(String.valueOf(max));buffer.append(value.charAt(pos));pos = i;max = 1;}}return buffer.toString();}}
题目真正的解法如下所示:
public static String countAndSay(int n) {if (n == 1) return "1";String s = "1";StringBuffer buffer = new StringBuffer();//记录重复的值int count = 0;// 迭代次数int round = 0;int i;while (++round < n) {count = 1;buffer.setLength(0);for (i = 1; i < s.length(); i++) {// 重复的值,继续计数if (s.charAt(i) == s.charAt(i - 1)) { count++;} else { // 有新的值出现,记录到bufferbuffer.append(count).append(s.charAt(i - 1));// 重置countcount = 1; }}buffer.append(count).append(s.charAt(i - 1));// 更新ss = buffer.toString(); }return buffer.toString();}
1 0
- Leetcode_38_count-and-say
- LOOK AND SAY
- 3438 Look and Say
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- Count and Say
- [38]Count and Say
- Count and Say
- Count and Say
- Count and Say
- [LeetCode]Count and Say
- Count and Say
- python第三方库系列之三--数据库迁移工具south库
- PHP中拼接sql(insert、update、replace)语句的三种方式
- 操作系统—存储管理
- 朵拉影像开发日志 11.18
- 如何在Hadoop2上远程调试MapReduce
- Leetcode_38_count-and-say
- 收集的部分C#中窗口句柄及操作
- 设计模式笔记-命令模式
- 五、Linux/UNIX操作命令积累【cp、mv、cat、grep、ps】
- 虚表详解
- java类加载器的粗略流程以及的ClassNotFound的加载原理
- 第十二周 项目一 程序阅读1-2
- listview+seekbar问题的解决
- php中的var