LeetCode OJ:Count and Say(数数)
2015-10-20 23:04
501 查看
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就是1,2前面是1就是1一个(11),3前面2个1就是(21),然后是(1211),再是(111221)以此类推。。。 当时题目看了半天没看懂,又去别的地方查了下题目是什么意思才知道了:
下面是java版本的,用了双指针,方法和上面的还是有一点不一样的:
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就是1,2前面是1就是1一个(11),3前面2个1就是(21),然后是(1211),再是(111221)以此类推。。。 当时题目看了半天没看懂,又去别的地方查了下题目是什么意思才知道了:
class Solution { public: string countAndSay(int n) { string curr = ""; if(n <= 0) return curr; curr = "1"; for(int i = 1; i < n; ++i){ curr = convert(curr); } return curr; } string convert(const string & prev){ //string result = ""; stringstream result; char last = prev[0]; int count = 0; int sz = prev.size(); for(int i = 0; i <= sz; ++i){//注意是<= if(prev[i] == last) count++; else{ result << count << last; // result.append(count); 这里append无法实现,因为找不到itoa,很蛋疼,只能用stream来实现 // result.append(last); last = prev[i]; count = 1; } } return result.str(); } };
下面是java版本的,用了双指针,方法和上面的还是有一点不一样的:
public class Solution { public String countAndSay(int n) { String s = String.valueOf(1);//很方便,直接就有类似itoa的api for(int i = 1; i < n; ++i){ s = say(s); } return s; } public String say(String s){ int sz = s.length(); int p2 = 0, p1 = 0; int count = 0; String ret = new String(""); while(p1 < sz){ while(s.charAt(p1) == s.charAt(p2)){ p1++; if(p1 == sz) //检查如果超过了长度就退出 break; } count = p1 - p2; ret = ret + String.valueOf(count) + s.charAt(p2); p2 = p1;//更新p2 } return ret; } }
相关文章推荐
- HA集群之一:HA Cluster基础理论及配置
- 数组作为函数参数时的使用注意
- CentOS配置本地yum源
- 更改百度云同步盘路径
- pct_free
- [Java] Struts2 - Validator 中文验证问题
- 小小菜之Cocos2d-x游戏开发旅程——项目实例:飞机大战(5)
- Android学习笔记-XML文件解析(一)
- Ionic 入门
- Node之tags
- tomcat:java.lang.outofmemoryerror permgen space
- LeetCode295——Find Median from Data Stream
- 日语学习ガス
- git branch(转)
- 归并排序的简单实现(c++ 版本)
- MonoDeveloper在Mac下快捷键记录
- 复购率
- 《平凡的世界》读后感
- 图片与素材网站
- [LeetCode]Reverse Linked List II