leetcode38---Count and Say
2016-01-15 09:59
483 查看
问题描述:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
也就是说:
输入n,那么我就打出第n行的字符串。
规律如下:
以此类推。(注意这里n是从1开始的)
问题求解:
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,那么我就打出第n行的字符串。
规律如下:
n = 1时,打印一个1。 n = 2时,看n=1那一行,念:1个1,所以打印:11。 n = 3时,看n=2那一行,念:2个1,所以打印:21。 n = 4时,看n=3那一行,念:一个2一个1,所以打印:1211。
以此类推。(注意这里n是从1开始的)
问题求解:
class Solution { public: string countAndSay(int n) { string ret = "1";//第一个序列 while(--n) {//循环再得到n-1个序列 int count = 1; string tmp; for(int i=1;i<ret.size();i++) { if(ret[i] == ret[i-1]) count++;//如果相等,不断累加 else {//如果不等,则把之前的字符个数和字符加到tmp,并将当前count置为1 tmp += to_string(count)+ret[i-1]; count = 1; } } //跑完循环之后把最后一个字符加上,因为之前只完成到了对第i个字符的计数 tmp += to_string(count)+ret.back();//ret.back()取字符串中最后一个字符 ret = tmp; } return ret; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [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 题解