38. Count and Say
来源:互联网 发布:淘宝网争议处理规则 编辑:程序博客网 时间:2024/06/15 18:47
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.
Note: The sequence of integers will be represented as a string.
public class Solution { public String countAndSay(int n) { String previous = "11"; if(n == 1){ return "1"; } if(n == 2){ return "11"; } StringBuffer result = new StringBuffer(); for(int i=3; i<=n; i++){ result.delete(0, result.length()); //每次读进来一个新的buffer int count = 1; for(int j=1; j<previous.length(); j++){ if(previous.charAt(j) == previous.charAt(j-1)){ count++; }else{ result.append(count); result.append(previous.charAt(j-1)); count = 1; //只有在加完之后才把count置位1 } if(j==previous.length() - 1){ //因为之前都是加的j-1,所以要把最后一个元素加进去 result.append(count); result.append(previous.charAt(previous.length() -1)); } } previous = result.toString(); } return result.toString(); }}
阅读全文
0 0
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 第四章 /proc/ 文件系统
- Subsets II (contains duplicates)
- CNN浅析和历年ImageNet冠军模型解析
- Microsoft SQL Server for Linux安装和配置
- 淘淘商城系列——Redis持久化方案
- 38. Count and Say
- 设有一组N个数,求其中第K个最大者
- 《算法分析与设计》Week 12
- CTF-浅尝64位栈溢出PWN
- Git笔记
- CreateThread 和_beginthreadex区别
- Python3网络爬虫(十二):初识Scrapy之再续火影情缘
- acm1004
- 如何申请TexturePacker注册码