[leetcode]38. Count and Say@Java
来源:互联网 发布:svd分解 对角矩阵 编辑:程序博客网 时间:2024/05/16 14:48
https://leetcode.com/problems/count-and-say/#/description
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 12. 113. 214. 12115. 111221
1
is read off as "one 1"
or 11
.11
is read off as "two 1s"
or 21
.21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1Output: "1"
Example 2:
Input: 4Output: "1211"
package go.jacob.day720;/** * 38. Count and Say * * @author Jacob * */// 思路:n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;// n=3时,由于上次字符是11,有2个1,所以输出21;// n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。// 依次类推,写个countAndSay(n)函数返回字符串。public class Demo2 {/* * 修改后的解答,使用StringBuilder 运行时间大大缩短 Runtime: 7 ms */public String countAndSay(int n) {if (n <= 0)return "";StringBuilder res = new StringBuilder();StringBuilder pre = new StringBuilder();res.append("1");for (int i = 1; i < n; i++) {pre = res;res = new StringBuilder();int count = 1;for (int j = 1; j < pre.length(); j++) {if (pre.charAt(j) == pre.charAt(j - 1)) {count++;} else {res.append(count).append(pre.charAt(j - 1));count = 1;}}res.append(count).append(pre.charAt(pre.length() - 1));}return res.toString();}/* * My Solution.Runtime: 44 ms */public String countAndSay_1(int n) {if (n <= 0)return "";String res = "1";for (int i = 1; i < n; i++) {String tmp = "";int count = 1;for (int j = 1; j < res.length(); j++) {if (res.charAt(j) == res.charAt(j - 1)) {count++;} else {tmp = tmp + count + res.charAt(j - 1);count = 1;}}tmp = tmp + count + res.charAt(res.length() - 1);System.out.println(tmp);res = tmp;}return res;}}
阅读全文
0 0
- Leetcode:38. Count and Say(JAVA)
- [LeetCode-Java]38. Count and Say
- [leetcode]38. Count and Say(java)
- [LeetCode] 38. Count and Say java
- [leetcode]38. Count and Say@Java
- [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]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
- React+router+redux兼容ie8下的页面效果
- 生兔子问题-看这一篇就够了
- 一文搞懂LSTM 网络
- Tiling (递推)
- 关闭键盘/收起键盘的方法总结(包括触摸UITableView收起键盘)
- [leetcode]38. Count and Say@Java
- linux驱动模型开发——linux platform总线机制讲解与实例开发
- 安卓性能优化之布局优化(二)
- Linux源码解析-进程-进程
- 17个新手常见Python运行时错误
- 使用两个栈实现一个队列+使用两个队列实现一个栈
- 千锋教育回应“骗子、骗局、坑”——浮言可以事久而明
- 阿里云备案类型介绍以及遇到的问题
- Codeforces Round #424 (Div. 2, )-树状数组|线段树-E. Cards Sorting