LeetCode Count and Say(java)
来源:互联网 发布:认知语言学与人工智能 编辑:程序博客网 时间:2024/05/21 19:11
题目有点难以理解,主要意思是在n=1时得到字符串“1”,然后在n=2时分析n=1时的字符串“1”,其中有1个1,所以得到新的字符串“11”,在n=3时,n=2的字符串“11”中为两个1,所以得到新的字符串“21”,在n=4时,n=3的字符串“21”为一个2一个1,所以得到字符串“1211”……依次类推对于每一个n返回一个字符串。
解题思路主要用到了递归的思想,通过解析n-1字符串得到n字符串。具体代码如下:
public String countAndSay(int n) { String s1="1"; if(n==1)return s1; String s=countAndSay(n-1); char[] sc=s.toCharArray(); StringBuilder sb=new StringBuilder(); int i=0; while(i<sc.length){ int count=1; while(i!=sc.length-1&&sc[i+1]==sc[i]){ count++; i++; } sb.append(count).append(sc[i]); i++; } return sb.toString(); }
阅读全文
0 0
- [Leetcode] Count and Say (Java)
- [LeetCode][Java] Count and Say
- count and say leetcode java
- LeetCode : Count and Say [java]
- LeetCode Count and Say(java)
- 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
- [LeetCode] Count and Say
- LeetCode-Count and Say
- LeetCode: Count and Say
- LeetCode - Count and Say
- [LeetCode] Count and Say
- SMOJ 2019 歌词 (AC自动机)
- 子类对象调用父类方法包含子类覆盖的方法
- Linux命令行及文件练习题
- 神器!!!简单一步就可以实现雷达图
- 指令系统的寻址方式大致汇总
- LeetCode Count and Say(java)
- 迭代求根
- 96. Unique Binary Search Trees
- 第四周 【项目5
- 计算等价类
- 二维码的生成细节和原理
- 呵呵
- 9.go开源groupcache项目笔记——lru代码
- CodeForces