77. Count and Say
来源:互联网 发布:直播讲课哪个软件 编辑:程序博客网 时间:2024/04/27 15:48
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 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 sequence.
分析:题目的要求是找出第n个序列。所以,要从n=1开始向后推算,通过第i-1个推出第i个直到通过第n-1个推出第n个。
从s1的最左侧开始数 ,看每个数字有几个。num vaule,依次又组成了下一个序列。
注意这个题目要在草稿纸上面进行推算之后,就会发现规律。
/** * 从1开始数。 * 首先得到第i-1个字符串,然后取通过这个字符串解析得到第i个字符串。 */public String countAndSay(int n) {if(n<=1){return "1";}String s1 = "1";//s1表示第i-1个数字表示的StringBuffer s = new StringBuffer();for(int i=1;i<n;i++){//通过i=1,计算得到的是i=2的结果int len = s1.length();for(int index = 0;index<len;){int num = 1;int value = s1.charAt(index)-48;//把char型转化成整数型数字index++;/*得出相等的数字有几个*/while(index<len && (s1.charAt(index)-48)==value){num++;index++;}s.append(num);s.append(value);}s1 = s.toString();s.delete(0, s.length());}return s1; }
也可以直接读出char型的数字,不进行到整数的转换。
/** * 从1开始数。 * 首先得到第i-1个字符串,然后取通过这个字符串解析得到第i个字符串。 */public String countAndSay2(int n) {if(n<=1){return "1";}String s1 = "1";//s1表示第i-1个数字表示的StringBuffer s = new StringBuffer();for(int i=1;i<n;i++){//通过i=1,计算得到的是i=2的结果int len = s1.length();for(int index = 0;index<len;){int num = 1;char value = s1.charAt(index);//读出char型的数字index++;/*得出相等的数字有几个*/while(index<len && s1.charAt(index)==value){num++;index++;}s.append(num);s.append(value);}s1 = s.toString();s.delete(0, s.length());}return s1; }
0 0
- 77. Count and Say
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- Count and Say
- [38]Count and Say
- Count and Say
- Count and Say
- Count and Say
- [LeetCode]Count and Say
- Count and Say
- Count and Say
- [LeetCode] Count and Say
- 动态内存分配
- poj_1000 A+B Problem 模拟
- hdu1024 Max Sum Plus Plus(最大子段和加强版)
- String和StringBuffe之可变与不可变
- Volley框架的使用
- 77. Count and Say
- 如何做系列(3)-Java数据类型和MySql数据类型对照表
- iOS开发UI篇:核心动画
- ZooKeeper使用
- The BulkProcessor class offers a simple interface to flush bulk operations automatically based on th
- 开始
- It’s Time to Move to a Four-Tier Application Architecture
- java2 -宏观了解
- 2014年第五届蓝桥杯C/C++程序设计本科B组省赛 切面条(结果填空)