LeetCode 38. Count and Say
2016-04-21 09:09
190 查看
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
I dont actually agree this is an easy one.... I made mistakes anyway....
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.
I dont actually agree this is an easy one.... I made mistakes anyway....
#include <string> #include <vector> #include <iostream> using namespace std; string nextString(string tmp) { string nextString = ""; for(int i = 0; i < tmp.size(); ++i) { int count = 1; while(i + 1 < tmp.size() && tmp[i] == tmp[i+1]) { i++; count++; } nextString += to_string(count) + tmp[i]; } return nextString; } string countAndSay(int n) { string tmp = "1"; for(int i = 1; i < n; ++i) { tmp = nextString(tmp); } return tmp; } int main(void) { cout << countAndSay(3) << endl; } // Second Version string nextStringII(string tmp) { string res = ""; int count = 1; for(int i = 1; i < tmp.size(); ++i) { if(tmp[i] == tmp[i-1]) { count++; } else { res += to_string(count) + tmp[i-1]; count = 1; } } int n = tmp.size(); if(count > 1) return res += to_string(count) + tmp[n - 1]; return res += to_string(count) + tmp[n-1]; }
相关文章推荐
- 寻找一个单向链表的中项,如果存在两个则返回前一个,给出算法描述
- JQ 1.9 API在线资源
- Django提交POST表单“CSRF verification failed. Request aborted”问题的解决
- wamp服务器
- centos 关闭防火墙
- spring框架学习(六)AOP
- 将Fragment加载到布局
- [调试] 打印类名方法名行数的Log日志
- hadoop,hbase,hive,zookeeper整合可行性分析及版本确定
- UITbaleView滚动到最后一行
- 第六周项目一
- 交通运输部·车载导航系统——终端如何与服务器通信——玩转通信协议(源码下载)
- 气象数据集数据和相关源码
- spring框架学习(五)注解
- SpringMVC源码剖析(一)- 从抽象和接口说起
- 18个最好的代码编辑器/IDE工具
- 第8周项目:【项目 1 -数组作数据成员】
- SVN相关
- [hdu 5521][2015ACM/ICPC亚洲区长春站] House Building
- 函数返回值的问题