# 题目链接

https://leetcode.com/problems/count-and-say/

# 解法

string read(string str){
string res = "";
int len = str.length();
if(str == "1") return "11";
int count = 1;
char num = str[0];
char temp;
int i = 1;
for(i = 1; i < len-1;i++)
{
if(str[i] == num)
{
count++;
}
else
{
temp = count + '0';
res = res + temp + num;
num = str[i];
count = 1;
}
}
if (str[i] == str[i-1])
{
count++;
temp = count + '0';
res = res + temp + num;
}
else
{
temp = count + '0';
res = res + temp + num;
res = res + "1" + str[i];
}
return res;
}

string countAndSay(int n){
string res = "1";
while(--n)
{
res = read(res);
}
return res;
}


4 ms, 在所有 C++ 提交中击败了85.15%的用户

string read(string str){
if(str == "1") return "11";
str = str + "x";
string res = "";
int index = 0;
int count = 1;
while(index < str.length()-1){
while(str[index] == str[index+1])
{
index++;
count++;
}
res += count + '0';
res += str[index];
count = 1;
index++;
}
return res;
}

string countAndSay(int n){
string res = "1";
while(--n){
res = read(res);
}
return res;
}


# 测试代码

#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int num = 0;
while(scanf("%d",&num)!= EOF)
{
cout<<countAndSay(num)<<endl;
}
return 0;
}


# 遇到问题

1.string类型变量末尾插入int型数字：

res += count + '0';


# 小结

posted @ 2020-05-18 22:46  陳浴巾  阅读(163)  评论(0编辑  收藏  举报