LeetCode : Count and Say [java]
2016-03-11 22:09
441 查看
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
思路:递归生成字符串,注意字符转字符串需要用String.valueOf()方法。
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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.
思路:递归生成字符串,注意字符转字符串需要用String.valueOf()方法。
public class Solution { public String countAndSay(int n) { String str = "1"; for (int i = 1; i < n; i++) { str = solve(str); } return str; } public String solve(String str) { String result = ""; char ch = str.charAt(0); System.out.println(ch); int count = 1; for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); if (ch == c) { count++; } else { char t = (char) (count + '0'); result += String.valueOf(t) + String.valueOf(ch); ch = c; count = 1; } } char t = (char) (count + '0'); result += String.valueOf(t) + String.valueOf(ch); return result; } }
相关文章推荐
- Java基础之&和&&或者|和||区别
- struts2标签库
- leetcode:268. Missing Number(Java)解答
- java通过构造方法为属性赋值
- java代码写xml文件
- 寒假笔记——java
- Example_java_测试
- Java——FileInputStream&FileOutputStream字节流实现文件复制
- 分布式Web应用----Java动态代理技术实现原理分析
- Java之Thread初使用
- java笔记-10
- java中初始化与构造器
- java笔记-9
- 最全SpringMVC具体演示样例实战教程
- java练习 - 字符串反转
- java笔记-7
- java笔记-6
- Java Web学习(六)
- Spring进阶之路(8)-java代码与配置文件中配置
- java笔记-5