题目描述:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

题目的意思是让我们数上一个字符串相邻的相同的数的个数,比如第4个字符为“1211”,则第5个字符串有一个1,一个2,两个1,组合起来就是“111221”。

例子:

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

解题思路:

这是一道递归类型的题,做这题时只要关注函数的结束条件和对上一个字符串的处理就行了。

代码:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         if(n==1)
 5         //结束条件
 6             return "1";
 7         string str=countAndSay(n-1)+'e';//结尾加上一个e,方便循环操作
 8         string tempStr="";//要返回的字符串
 9         int count = 1;
10         for(int i=0;i<str.length()-1;i++){
11             if(str[i]==str[i+1])
12                 count++;
13             else{
14                 tempStr=tempStr+to_string(count)+str[i];
15                 //int型转string型的一个函数(浮点数和整数都可以转)
16                 count=1;
17             }
18         }
19         return tempStr;
20     }
21 };

 

posted on 2018-02-02 12:29  宵夜在哪  阅读(111)  评论(0编辑  收藏  举报