leetcode题解-38. Count and Say
来源:互联网 发布:gallery3d源码分析 编辑:程序博客网 时间:2024/06/06 02:49
题意:计数和发言。
n=1时输出字符串1;
n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
n=3时,由于上次字符是11,有2个1,所以输出21;
n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
依次类推,写个countAndSay(n)函数返回字符串。
分析:这道题属于字符串操作的类型,算法上提高空间不大,只能是从n=1开始模拟,读过去然后得到计数并生成下一个串。时间复杂度是O(n*串的长度),空间复杂度是O(串的长度)。
值得注意的是,跑完循环之后记得把最后一个字符也加上,因为之前只是计数而已。这道题属于字符串或者说数组操作的类型,考察对于明确问题和算法的实现能力,一般会在电面,或者最容易的第一道题中出现。
代码如下:
class Solution { public String countAndSay(int n) { String str = "1"; for(int i = 0; i < n - 1; i++){ str = SayNext(str); } return str; } public String SayNext(String str) { int len = str.length(); StringBuilder sb = new StringBuilder(); int i = 0, j = 1; while(j < len){ if(str.charAt(i) == str.charAt(j)){ j++; }else{ sb.append(j - i + "" + str.charAt(i)); i = j; } } sb.append(j - i + "" + str.charAt(i)); return sb.toString(); }}
阅读全文
0 0
- leetcode题解-38. Count and Say
- Leetcode题解-38. Count and Say
- LeetCode题解:Count and Say
- leetcode题解-686. Repeated String Match && 38. Count and Say
- LeetCode题解:Count and Say解法
- leetcode 题解 || Count and Say 问题
- LeetCode题解——Count and Say
- LeetCode 题解(230) : Count and Say
- [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
- 回文判断
- Matlab实现 理想低通、巴特沃斯低通、高斯低通、理想高通、巴特沃斯高通、高斯高通(d=10,50,150)
- 深度递归学习
- Linux 命令
- 1.笔记 5.7.10MySQL——安装
- leetcode题解-38. Count and Say
- 4. 卷2(进程间通信)---管道和FIFO
- 隐马尔科夫模型(二)
- centos安装golang、protobuf
- 1、IT学习班——流程图制作之安装与下载
- 随便记点,静态类,tostring()方法
- ios11新特性
- adlist
- 线程安全