[leetcode]Count and Say
2014-07-16 20:42
183 查看
Count and Say
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. 扫描迭代,逐个处理,没啥难度。
2. 递归实现。
3. 这道题的难度表推荐算法是dfs,因此这一遍我用dfs实现了一遍,其实感觉木有必要,迭代已经很简单了。
迭代算法如下:
递归实现如下:
dfs算法如下:
The count-and-say sequence is the sequence of integers beginning as follows:
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. 扫描迭代,逐个处理,没啥难度。
2. 递归实现。
3. 这道题的难度表推荐算法是dfs,因此这一遍我用dfs实现了一遍,其实感觉木有必要,迭代已经很简单了。
迭代算法如下:
public class Solution { public String countAndSay(int n) { if (n <= 0) { return null; } String s = "1"; int num = 1; for (int j = 0; j < n - 1; j++) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) { num++; } else { sb.append(num + "" + s.charAt(i)); num = 1; } } s = sb.toString(); } return s; } }
递归实现如下:
public class Solution { public String countAndSay(int n) { if(n <= 0) return ""; if(n == 1) return "1"; String pre = countAndSay(n - 1); int length = pre.length(); int from = 0, to = 0; StringBuilder sb = new StringBuilder(); while(to < length){ while(to + 1< length && pre.charAt(to) == pre.charAt(to + 1)) to++; sb.append(to - from + 1).append(pre.charAt(from)); from = to + 1; to = from; } return sb.toString(); } }
dfs算法如下:
public class Solution { String s = "1"; public String countAndSay(int n) { if(n < 1) return ""; for (int i = 1; i < n; i++) dfs(s.length()); return s; } private void dfs(int length) { if (length == 0) return; int count = 1, i = 0; while (i < length - 1 && s.charAt(i) == s.charAt(1 + i)) { count++; i++; } s = s.substring(i + 1) + count + s.charAt(i); dfs(length - count); } }
相关文章推荐
- [LeetCode]题解(python):038-Count and Say
- LeetCode——Count and Say
- leetcode-38 Count and Say
- leetcode之count and say
- [C++]LeetCode: 20 Count and Say
- leetcode由易入难——【6】Count and Say
- Leetcode|Count and Say
- LeetCode 38 Count and Say(C,C++,Java,Python)
- LeetCode38 Count and Say(C语言解决)
- [leetcode]50 Count and Say
- [Leetcode]38--Count and Say
- LeetCode38 - Count and Say
- leetcode第一刷_Count and Say
- [Leetcode]Count and Say
- LeetCode: Count and Say 题解
- leetcode:Count and Say
- leetcode笔记--Count and Say
- LeetCode-Count and Say
- Leetcode || Count and Say
- [LeetCode]Count and Say