# Leetcode Count and Say 数数列数字

Count and Say

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=2的时候数数列1有什么数字； n=3的时候数数列2有什么数字； n=4的时候数数列3有什么数字……

class Solution {
public:
string countAndSay(int n)
{
if (n == 0) return "";
string str = "1";
for (int i = 1; i < n; i++)
{
char ch = '0';
string str2 = "";
int counting = 0;
for (int j = 0; j < str.length(); j++)
{
if (str[j] == ch) counting++;
else
{
if (counting > 0)
str2 = str2 + char(counting + '0') +ch;
counting = 1;
ch = str[j];
}
}
str2 = str2 + char(counting + '0') +ch;
str = str2;
}
return str;
}
};

下面是leetcode上比较不错的算法：

http://discuss.leetcode.com/questions/217/count-and-say

class Solution {
public:
string getNext(string &s)
{
if(s == "") return "1";
string temp = "";
for(int i = 0; i < s.size(); i++) {
int cnt = 1;
while(i+1 < s.size() && s[i] == s[i+1]) {
i++;
cnt++;
}
stringstream ss;
ss << cnt;
temp += ss.str();
temp += s[i];
}
return temp;
}
string countAndSay(int n)
{
string s = "";
if(n == 0) return s;

for(int i = 0; i < n; i++) {
s = getNext(s);
}
return s;
}
};

更新下面的程序更加清晰快速点，4ms

//2014-1-26
class Solution {
public:
string countAndSay(int n)
{
string rs;
string tmp;
if (n==0) return rs;
rs.push_back('1');

for (int i = 1; i < n; i++)
{
int c = 1;//注意：牢记每次都需要重置的时候一定要重置，否则答案错误！！！
for (int j = 1; j < rs.length(); j++)
{
if (rs[j] == rs[j-1]) c++;
else
{
tmp.push_back(c+'0');
tmp.push_back(rs[j-1]);
c = 1;
}
}
tmp.push_back(c+'0');
tmp.push_back(rs.back());
rs.clear();
rs.swap(tmp);
}
return rs;
}
};


#### Count and say

2014-10-16 11:27:31

#### LeetCode 38 Count and Say（字符串生成）

2017-07-08 08:47:08

#### leetCode 38.Count and Say (计数和发言) 解题思路和方法

2015-07-09 20:40:16

#### Count and Say

2016-07-25 10:34:17

#### LeetCode --- Count And Say

2015-07-23 09:27:05

#### LeetCode 38 Count and Say(C,C++,Java,Python)

2015-05-19 21:36:24

#### leetcode -- Count and Say -- 理解题意

2015-12-09 11:45:44

#### LeetCode38 Count and Say(C语言解决)

2016-11-15 12:13:21

#### LeetCode --- 38. Count and Say

2015-02-05 23:33:41

#### LeetCode-38-Count and Say(String/递归)-Easy

2016-01-03 10:47:14