LeetCode | Count and Say
2013-12-26 23:02
375 查看
题目:
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.
思路:
题目理解比较费时,就是一个常规的递归问题。
代码:
class Solution { public: string countAndSay(int n) { if(n==1) { return "1"; } else if(n==2) { return "11"; } else { string str = countAndSay(n-1); string result; int pre; int cur=str[0]-'0'; int count=1; for(int i=1;i<str.size();i++) { pre=cur; cur=str[i]-'0'; if(pre==cur) { count++; } else { result.push_back(count+'0'); result.push_back(pre+'0'); count=1; } } result.push_back(count+'0'); result.push_back(cur+'0'); return result; } } };
相关文章推荐
- LeetCode-38-Count and Say Python的int_to_string
- leetcode——38——Count and Say
- [LeetCode] Count and Say
- [leetcode] Count and Say
- 【leetcode c++】38 Count and Say
- LeetCode---Count and Say
- leetcode_c++:Count and Say(038)
- 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刷题(C++)——Count and Say(Easy )
- Leetcode 38 Count and Say
- 《leetCode》:Count and Say
- leetcode_Count and Say
- 【Leetcode】【python】Count and Say
- LeetCode-38-Count and Say-E
- leetcode-38-Count and Say