【LeetCode】Count and Say
2014-06-10 21:45
465 查看
题目描述:
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
一开始考虑会不会出现统计大于9的情况,懒得自己写int转string,就想用itoa,提交了下发现CE,索性就忽略这种情况直接提交吧,果然过了……看了下test case只有18个。
没什么难点,就是统计下重复元素的个数,用s[i-1]==s[i]可以很方便的判定。
代码如下:
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.
一开始考虑会不会出现统计大于9的情况,懒得自己写int转string,就想用itoa,提交了下发现CE,索性就忽略这种情况直接提交吧,果然过了……看了下test case只有18个。
没什么难点,就是统计下重复元素的个数,用s[i-1]==s[i]可以很方便的判定。
代码如下:
class Solution { public: string countAndSay(int n) { string res = "1"; for (int i = 1; i < n; i++){ int count(0); string s; for (int j = 0; j < res.length(); j++){ if (j>0 && res[j - 1] != res[j]){ s += '0' + count; s += res[j - 1]; count = 0; } count++; } s += '0' + count; s += res[res.length() - 1]; res = s; } return res; } };
相关文章推荐
- LeetCode刷题笔录Count and Say
- LeetCode --- Count And Say
- [LeetCode 38] Count and Say
- 【LeetCode-面试算法经典-Java实现】【038-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_Count and Say
- 【Leetcode】【python】Count and Say
- 【Leetcode】Count and Say
- leetcode Count and Say
- Leetcode--Count and Say
- [leetcode][string] Count and Say
- Leetcode NO.38 Count and Say
- Leetcode 38 Count and Say 传说中的递推
- leetcode[38]:Count and Say
- leetcode ——Count and Say
- LeetCode——Count and Say