[leetcode][string] Count and Say
2015-05-13 19:49
381 查看
题目:
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.
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) { string res; if (n < 0) return res; res = "1"; for (int i = 1; i < n; ++i){ string tmp; int j = 0; int cnt = 0; for (; j < res.size(); ++j){ if (j == 0 || res[j] == res[j - 1]) {
<span style="white-space:pre"> </span>++cnt;
<span style="white-space:pre"> </span>continue;
<span style="white-space:pre"> </span>} tmp.push_back(cnt + '0');//前一个字符的个数 tmp.push_back(res[j - 1]);//前一个字符 cnt = 1;//!!!当前的字符个数是1个 } //!!!最后一组 tmp.push_back(cnt + '0'); tmp.push_back(res[j - 1]); res = tmp; } return res; } };注意:在当前字符不同于前一个字符时才可以确定前一组
相关文章推荐
- [LeetCode] Count and Say (使用java string 体会)
- leetcode_38题——Count and Say(string,迭代计数)
- **(leetcode_string) Count and Say
- LeetCode-38-Count and Say Python的int_to_string
- LeetCode 之 Count and Say
- LeetCode: Count and Say
- [leetcode]Count and Say
- LeetCode Online Judge 题目C# 练习 - Count and Say
- LeetCode-Count and Say
- LeetCode力扣之Count and Say
- [LeetCode] Count and Say
- LeetCode: count and say
- 38.leetcode Count and Say(easy)[字符串处理 string与int的转换]
- [LeetCode] Count and Say
- 【Leetcode】【python】Count and Say
- 【LeetCode38】【Count and Say】StringBuilder
- LeetCode-Count and Say
- 37 leetcode - Count and Say
- (leetCode)Count and Say --- 统计读
- LeetCode_Count and Say