LeetCode(38) Count and Say
来源:互联网 发布:多功能工具 知乎 编辑:程序博客网 时间:2024/05/20 02:29
题目
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.
分析
这是一道根据规则推导题目,要求给定序列数n,求出该序列对应的字符串。
规则如上图所示。
AC代码
class Solution {public: string countAndSay(int n) { if (n <= 0) return NULL; //n=1时,结果为"1" string ret = "1"; if (n == 1) return ret; else { for (int i = 2; i <= n; i++) ret = Count(ret); }//else return ret; } string Count(const string &str) { int size = strlen(str.c_str()); //保存结果 stringstream ret; //保存标识字符 char flag = str[0]; //计算标识字符的出现次数 int count = 0 , i = 0; while( i < size ) { //临时循环位 int pos = i; while (str[pos] == flag) { count++; pos++; }//while ret << count << flag; flag = str[pos]; count = 0; //设置下一个循环位 i = pos; }//for return ret.str(); }};
GitHub测试程序源码
0 0
- LeetCode(38) Count and Say
- [LeetCode 38] Count and Say
- LeetCode(38) Count and Say
- [leetcode 38] Count and Say
- [Leetcode] 38 - Count and Say
- leetcode-38 count and say
- [LeetCode 38]Count and Say
- LeetCode 38 Count and Say
- leetcode-38 Count and Say
- Leetcode 38 Count and Say
- Leetcode---(38)Count and Say
- leetcode 38: Count and Say
- Leetcode# 38 Count and Say
- leetcode[38]:Count and Say
- leetcode-38 Count And Say
- [Leetcode]#38 Count and Say
- LeetCode 38 Count and Say
- leetcode 38:Count and Say
- 360兼容模式 SCRIPT1028: 缺少标识符、字符串或数字
- cmd进入mysql的方法
- Hadoop-0.22.0分布式集群配置
- ionic 实现广告图片无限滚动标签介绍
- Unity3D热更新全书-何谓热更新,为何热更新,如何热更新
- LeetCode(38) Count and Say
- java.io.IOException: open failed: EACCES (Permission denied)问题解决
- 归并排序-MergeSort
- 如何订阅一个Free Trial的Office 365账户
- 我的博客迁移到 www.zhenghongzhi.cn
- 通过bash实现linux系统账户审计功能
- Makefile与Kconfig和.config关系与使用
- url中?的作用
- 环境污染:无形的灾难【经济学人】