Count and Say 笔记

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

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.
Given an integern, generate thenthterm of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.

题目意思大概就是,n = 1时候输出一个1,n = 2的时候输出11(1个1),n = 3 时候输出 21(2个1),n = 4时候输出1211(1个2,1个1)。。。以后每个数相当于把前头的数数一遍。

思路:写个循环,从2开始一直循环到n,用两个字符串分别保存上一个数的结果和这次的结果。循环里,再来一个循环数字符串。两个变量,一个a保存现在正在数的字符,一个ac用来保存正在数的字符的个数。每次循环完把res2的值赋值给res,下次循环用。简单粗暴的解决了。

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        string res2 = "1";
        //从2开始数 
        for(int i = 2; i<= n;i++)
        {
            res2 = "";
            char a = res[0];//数 第一个数 
            int ac = 1; //计数
            int j = 1;// 
            while(res[j]!='\0')//结束
            {
                if(res[j] == a)//计数加1 
                {
                    ac++;
                    j++; 
                }
                else //加这个 
                {
                    char temp[200] = ""; 
                    sprintf(temp,"%d",ac);
                    res2 += temp;
                    res2 += a;
                    a = res[j];
                    ac = 1;
                    j++;
                } 
            }
            char temp[200] = ""; 
            sprintf(temp,"%d",ac);
            res2 += temp;
            res2 += a; 
            res = res2;
        } 
        return res2;
    } 
};
int main()
{
    Solution so;
    for(int i = 0;i<=10;i++)
    {
        string ss = so.countAndSay(i);
        cout << i << " "<< ss << endl;  
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,487评论 0 23
  • 这个星期在学画画,而在看高手的教学中,明白了很重要的一点,就是一直在做一件事,而遇到瓶颈时,要懂得换下位,就像长时...
    愿若水阅读 2,383评论 0 0
  • 今天听了紫雨老师的《什么叫投射》,原来之前的投射都错了,没有从正确的感觉源点出发,只是应付糊弄,以后好好做投射,哈...
    许晓凌_中阅读 1,085评论 0 0