leetcode刷题日记——Count and Say
来源:互联网 发布:软件系统测试 编辑:程序博客网 时间:2024/06/13 20:34
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.
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,返回序列的第n个元素。注意到题目不仅仅是统计各种元素的个数,当序列中元素发生改变的同时,需要重新计数。这一点很重要。其他操作都比较好理解。另外因为最终要将计数值的整数形转化为字符串然后用+号连接起来生成新的字符串,to_string 方法的使用,具体实现代码如下:
class Solution {public: string countAndSay(int n) { if (n<2) return "1";string pre = "1";map<char, int> count;for (int i = 1; i<n; i++){int length = pre.size();int count = 1;char xx = pre[0];string ss = "";for (int j = 1; j<length; j++){if (pre[j] == xx) count++;else{ss += to_string(count);ss += xx;xx = pre[j];count = 1;}}ss += to_string(count);ss += xx;pre = ss;}return pre; } };
0 0
- leetcode刷题日记——Count and Say
- LeetCode刷题笔录Count and Say
- leetcode ——Count and Say
- LeetCode——Count and Say
- LeetCode——Count and Say
- leetcode记录——Count and Say
- leetcode 038 —— Count and Say
- LeetCode题解——Count and Say
- [LeetCode]—Count and Say 读数字
- 刷Leetcode:Count and Say
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- [LeetCode]Count and Say
- 二叉排序树的构建及验证
- Github logo in LaTeX
- 数据结构C语言版之线性表
- 2659: [Beijing wc2012]算不出的算式
- LinearLayout中的属性baselineAligned的使用
- leetcode刷题日记——Count and Say
- Eclipse 高亮显示选中的相同变量
- log4j.properties配置详解与实例
- 整理的各种IDE调整内存限制的方法,看看有没有你需要的
- 机器学习种类(三)
- 数据结构C语言版之二叉树操作
- Linux 下编译 redis 报错解决办法
- OC学习篇之-----内存管理
- 数据结构C语言版之邻接表(各种遍历)