Count and Say:循环记录字符串中数字个数
来源:互联网 发布:2016淘宝刷单 编辑:程序博客网 时间:2024/06/10 10:54
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"思路:这题不容易读明白,可以理解为:
At the beginning, I got confusions about what is the nth sequence. Well, my solution is accepted now, so I'm going to give some examples of nth sequence here. The following are sequence from n=1 to n=10:
1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211
From the examples you can see, the (i+1)th sequence is the "count and say" of the ith sequence!
即i=5时,从左往右扫描字符串4,发现有一个1,一个2,两个1,于是写作111221.看懂样例,模拟就行。
class Solution { public String countAndSay(int n) { if(n<=0) return ""; String r = "1"; for(int i = 1;i<n;i++){ StringBuilder b = new StringBuilder(); int count = 1; char t = r.charAt(0); for(int j =1;j<r.length();j++){ if(r.charAt(j)==t){ count++; }else{ b.append(count).append(t); t = r.charAt(j); count = 1; } } b.append(count).append(t); r = b.toString(); System.out.println(r); } return r; }}
阅读全文
0 0
- Count and Say:循环记录字符串中数字个数
- 【字符串】Count and Say
- 字符串---Count and Say
- Count and Say 数字统计
- leetcode---count-and-say---字符串
- Leetcode Count and Say 数数列数字
- leetcode_38. Count and Say 统计数字个数并说出来,组成新的字符串
- leetcode记录——Count and Say
- 个人记录-LeetCode 38. Count and Say
- [leetcode] 【字符串】 38. Count and Say
- 3.12—字符串—Count and Say
- 字符串的统计字符串(count and say类似题目)
- 【C++】数数:用数字来数数Count and Say
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Count and Say
- 软件人生感触之一 深度和广度
- [deeplearning-003] 一般形式的反向传导算法BP最简推导-1
- day 9 Linux
- [队列]【NOIP2016D2T2】蚯蚓 题解
- String和StringBuffer以及StringBuilder的区别
- Count and Say:循环记录字符串中数字个数
- 客户端与服务端长连接Mina框架讲解
- 利用Turbo C进行平面二维图形的平移,旋转,缩放,对称
- 10w定时任务,如何高效触发超时
- 【第05章】【ByteBuf】
- Java——下载窗体案例
- 线性筛法求素数的原理与实现
- 阿里JAVA开发手册零度的思考理解(一)
- 總結——關於2017 10 26測試的分析總結