Count and Say
2015-09-16 20:27
274 查看
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.
思路:题目很简单,看清题意,代码如下:
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.
思路:题目很简单,看清题意,代码如下:
class Solution { public: string countAndSayOnce(string s){ string ret = ""; int i = 0, len = s.length(); while(i++ < len){ int count = 1; while(i < len && s[i] == s[i - 1]){ count ++; i++; } ret += count + '0'; ret += s[i - 1]; } return ret; } string countAndSay(int n) { string s = "1"; for(int i = 0; i < n - 1; ++i) s = countAndSayOnce(s); return s; } };
相关文章推荐
- 短信发送
- 设计模式 装饰者模式
- [家里蹲大学数学杂志]第418期南开大学2013年实变函数期末考试试题参考解答
- Very simple problem - SGU 111(大数开方)
- Linux的SOCKET编程详解
- LNMP之memcached实现tomcat群集(三)
- c语言命名空间,cin.get().cin.getline()
- 开源框架DBUtil的使用以及使用Threadlocal类控制事务案例
- ListView--QQ联系人样式
- UIWindow
- LeetCode_OJ【21】Merge Two Sorted Lists
- HDU 1754 线段树
- android解析JSON,XML数据的请求网络工具类
- 类的一般继承与虚继承
- 国外程序员整理的Java资源大全
- HDU 1394(逆序数)
- 设计模式 观察者模式 以微信公众服务为例
- flex通过HTTPService与java通信例子
- UIApplication
- 药品搜索开发API接口-查询药品信息