[LeetCode] Count and Say
2015-11-17 13:13
549 查看
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.
题意: 读数字,开始是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
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解