[Leetcode]Count and Say
2014-11-02 15:46
344 查看
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.
思路很简单,从1开始一个一个数数到n。数1的时候,产生一个StringBuilder用来维护第一个的读音,也就是“11”。然后把“11“作为输入继续数,可用递归, 每递归一层加1.
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.
思路很简单,从1开始一个一个数数到n。数1的时候,产生一个StringBuilder用来维护第一个的读音,也就是“11”。然后把“11“作为输入继续数,可用递归, 每递归一层加1.
public String countAndSay(int n) { String num = "1"; int countAll = 1; return countAndSay(num, countAll, n); } private String countAndSay(String num, int countAll, int n) { if (countAll >= n) { return num; } StringBuilder sb = new StringBuilder(); int count = 1; for (int i = 0; i < num.length() - 1; i++) { if (num.charAt(i) == num.charAt(i + 1)) { count++; } else { sb.append(count); sb.append(num.charAt(i)); count = 1; } } sb.append(count);//最后跳出循环要考虑append上最后一串的count and say sb.append(num.charAt(num.length() - 1)); num = sb.toString(); return countAndSay(num, countAll+1, n); }
相关文章推荐
- 【leetcode】Count and Say
- LeetCode | Count and Say
- LeetCode--Count and Say(Python)
- leetcode 38:count and say
- LeetCode 38:Count and Say
- leetcode做题总结,题目Count and Say 2012/03/05
- [leetcode]Count and Say
- LeetCode-Count and Say
- LeetCode-38-Count and Say(String/递归)-Easy
- Leetcode 38 Count and Say
- LeetCode Count and Say
- LeetCode38——Count and Say
- [Leetcode 38, Easy] Count and Say
- LeetCode : Count and Say [java]
- leetcode 38: Count and Say
- 【LeetCode 38_字符串_算术运算】Count and Say
- [leetcode-38]Count and Say
- Count and say[easy on LeetCode]
- [LeetCode] Count and Say 字符串
- LeetCode - Count and Say