【leetcode】38. Count and Say
2016-06-26 11:12
399 查看
一、题目描述
The count-and-say sequence is the sequence of integers beginning as follows:
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,1个1所以第二数字是11,2个1所以第三个数字是21,1个2和1个1所以第四个数字是1211.... 按这种规律类推
思路:从第三个开始,从1~n-1,对每个数字计数。每次都与前一个进行比较,相同就计数+1,否则就先把前一个数的个数+值存入结果字符串中。
c++代码(20ms,1.11%)
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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,1个1所以第二数字是11,2个1所以第三个数字是21,1个2和1个1所以第四个数字是1211.... 按这种规律类推
思路:从第三个开始,从1~n-1,对每个数字计数。每次都与前一个进行比较,相同就计数+1,否则就先把前一个数的个数+值存入结果字符串中。
c++代码(20ms,1.11%)
class Solution { public: string countAndSay(int n) { string s="11"; if(n==1) return "1"; if(n==2) return "11"; for(int i=2;i<n;i++){ string str=""; for(int j=1;j<s.size();j++){ int count=1; while(s[j] == s[j-1] && j<s.size()){ count++; j++; } stringstream ss,cc; ss<<count; cc<<s[j-1]; str+=ss.str()+cc.str(); if(j==(s.size()-1) && s[j]!=s[j-1]){ int i=1; stringstream mm,nn; mm<<i; nn<<s[j]; str+=mm.str()+nn.str(); } }//for s=str; } return s; } };
相关文章推荐
- [JZOJ4512][JSOI2016]最佳团队
- java实现倾斜水印铺满整张图
- 不要依赖apue.h
- Java网络编程URL和URI
- EhCache Monitor的使用
- java中的url和uri
- qwt中常用的接口函数
- 浅谈JavaSE工厂模式重要性
- C++中虚函数工作原理和(虚)继承类的内存占用大小计算
- 欢迎使用CSDN-markdown编辑器
- URI和URL的区别
- openGL学习进程(1)OpenGL的简介
- c++中强制类型转换操作符小结
- Java对URL和URI的区分
- #ifdef 与或 条件
- 共价大爷游长沙
- 利用管道进行进程的通信示例
- 单片机中断总结
- 轮播广告的实现
- OpenSessionInView详解