【Leetcode】38. Count and Say
来源:互联网 发布:淘宝店铺换ip有影响吗 编辑:程序博客网 时间:2024/05/29 16:59
方法一:非递归
思路:
(1)依次求第i个String。
(2)每一次求解,用temp保存暂时的结果,求解后赋给result。
(3)遍历每个result,j记录待判断个数的字符,k用于判断,一旦与j字符不等,立即写入temp。
public class Solution { public String countAndSay(int n) { String result = "1"; for (int i = 2; i <= n; i++) { String temp = ""; int j = 0, k = 1, len = result.length(); while (j < len) { char ch = result.charAt(j); if (k < len && ch == result.charAt(k)) k++; else { temp += (k - j); temp += ch; j = k; } } result = temp; } return result; }}
方法二:递归
思路:
先求第n-1个序列res,再遍历res,j记录待判断个数的字符,k用于判断,一旦与j字符不等,立即写入temp。
public class Solution { public String countAndSay(int n) { if (n == 1) return "1"; String res = countAndSay(n - 1); String result = ""; int j = 0, k = 1, len = res.length(); while (j < len) { char ch = res.charAt(j); if (k < len && ch == res.charAt(k)) k++; else { result += (k - j); result += ch; j = k; } } return result; }}Runtime:54ms
1 0
- [LeetCode]38.Count and Say
- LeetCode --- 38. Count and Say
- LeetCode 38.Count and Say
- [Leetcode] 38. Count and Say
- 38. Count and Say LeetCode
- Leetcode 38. Count and Say
- leetcode 38. Count and Say
- [leetcode] 38. Count and Say
- LeetCode-38.Count and Say
- LeetCode *** 38. Count and Say
- leetcode 38. Count and Say
- LeetCode-38. Count and Say
- LeetCode 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode - 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode 38. Count and Say
- LeetCode 38. Count and Say
- 【备忘】北风网Android应用实战淘宝网手机客户端全程实录 下载
- AndroidAnnotations注解说明
- pat-a1084. Broken Keyboard (20)
- 常用的表扩展字段方案
- Python 装饰器归纳总结
- 【Leetcode】38. Count and Say
- Docker完全解析 一、Docker简介
- Ubuntu安装Tomcat8
- OP整流电路
- FZU 1036 四塔问题
- 知识库--StandardContextMapper(60)
- 6
- 第一次使用Android Studio时你应该知道的一切配置
- Java做acm所需要的基础知识之基本输入输出问题