[LeetCode] Count and Say
来源:互联网 发布:windows 2008 加入域 编辑:程序博客网 时间:2024/06/16 12:15
Count and Say
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
” or11
.
11
is read off as “two 1s
” or21
.
21
is read off as “one 2
, thenone 1
” or1211
.
Given an integer n, generate the nth sequence.Note: The sequence of integers will be represented as a string.
- 题意: 读数字,开始是1,然后是两一个一(1 1),然后是两个一(2 1),然后是一个二一个一(1 2 1 1).求第n次的结果,存成字符串返回.
- 解法: 嘛,其实感觉这题没意思,因为数字太大的话,时间会很长.数据小的话,就没意思了,因为数字的连续数量不会超过9个,总之,直接模拟就好了,用两个串来记当前串和下一串,读当前串结果存在下一串,然后读下一串,读的过程就是两个for循环,第一重是枚举第i个数,然后跳到下一个与i不同的数,第二重就是一直循环把相同的数跑完就好了,然后用j-i得出连续的数有多少个.复杂度:O(n*m)m在递增,一次比一次长.数据大概应该是只有1到18吧.18组测试数据.
class Solution {public: string countAndSay(int n) { string akResult[2]; int iCurIdx = 0; for (akResult[iCurIdx].push_back('1'); --n; iCurIdx ^= 1) { akResult[iCurIdx ^ 1].clear(); for (int i = 0, j = 0; i < (int)akResult[iCurIdx].size(); i = j) { for (j = i; j < (int)akResult[iCurIdx].size() && akResult[iCurIdx][j] == akResult[iCurIdx][i]; ++j); akResult[iCurIdx ^ 1].push_back((j - i) + '0'); akResult[iCurIdx ^ 1].push_back(akResult[iCurIdx][i]); } } return akResult[iCurIdx]; }};
欢迎访问我的github,我的leetcode持续更新: https://github.com/tsfissure/LeetCode
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 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
- Count and Say 【leetcode】
- [LeetCode] Count and Say
- Leetcode Count and Say
- LeetCode Count and Say
- LeetCode | Count and Say
- Android 内存管理介绍
- 使用CreateRemoteThread把代码远程注入指定exe执行
- 黑马程序员--冒泡排序
- 协程
- iOS - 设置cell显示还是不显示机制
- [LeetCode] Count and Say
- 欢迎使用CSDN-markdown编辑器
- freemarker实现和原理
- JS gzip加密字符串并base64输出
- LinearLayout和RelativeLayout的特殊属性
- 如何免费试用访问Google
- HTML中id与name的区别
- 安装Fedora 23后需要做几件事
- Cookie/Session机制详解