38. Count and Say
2016-05-27 19:21
281 查看
38. Count and Say
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.
Analysis:
不复杂,主要是依次判断当前digit和上一个digit是否相同。
Source Code(C++):
#include <iostream> #include <string> #include <map> #include <vector> using namespace std; class Solution { public: string countAndSay(int n) { string s="1"; for (int i=0; i<n-1; i++) { //第一个已经求出,只需要循环n-1次即可 int index=0; int same_digit_counts=0; string next_string; while(index < s.size()) { if (index == 0) { same_digit_counts=1; } else if (s.at(index) == s.at(index-1)) { same_digit_counts++; } else { next_string.push_back(char(same_digit_counts+'0')); next_string.push_back(s.at(index-1)); same_digit_counts=1; } index++; } next_string.push_back(char(same_digit_counts+'0')); next_string.push_back(s.at(index-1)); s=next_string; } return s; } }; int main() { Solution sol; cout << sol.countAndSay(5); return 0; }
相关文章推荐
- 职员有薪水了
- Apache服务器配置
- ajax返回200 ok但一直进入error而不是success
- php+linux的crontab实现定时抓取csdn文章到mysql数据库
- 0525《构建之法》8、9、10章读后感
- IBatis一对多查询
- 二叉树--红黑树
- git学习参考网站
- C#—实验9.1、9.2、9.3和9.4
- iOS:在objective-c 使用可变参数
- 泛型
- Android动画-Property Animation(一)
- 数据结构——栈
- Maven 常用命令
- 函数模板和模板函数
- 深入理解递归函数的调用过程
- Ajax教程—用户名是否被注册之案例篇(三)
- Makefile经典教程
- bzoj 3112: [Zjoi2013]防守战线 单纯形
- webservice 客户端 调用服务端 进行测试