• 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.

    思路:这道题主要是通过1这个数字产生,得出11,然后21,再然后1211。。。。就是通过上一个字符串中有几个1几个2等等,产生出下一个字符串。每一次对一个字符串循环计数,首先设置一个初始变量,计算第一个数字出现了几次,cont++;如果不等于,在开始将原有字符串中+count+上一次数字,将这个字符赋值给这个变量,count初始化为1,进行下次循环。就可以得到这个字符串应有的结果。

    class Solution {
    public:
        string countSay(const string &str)
        {
            string result;
            char temp=str[0];
            int count=1;
            int n=str.size();
            char count_ch;
            for(int i=1;i<n;i++)
            {
                if(str[i]==temp)
                {
                    count++;
                }
                else
                {
                    count_ch=count+'0';
                    result=result+count_ch+temp;
                    temp=str[i];
                    count=1;
                }
            }
            count_ch=count+'0';
            result=result+count_ch+temp;
            return result;
        }
        string countAndSay(int n) {
            string say="1";
            for(int i=1;i<n;i++)
            {
                say=countSay(say);
            }
            return say;
        }
    };
  • 相关阅读:
    config Doku wiki
    [转载]【python】ipython与python的区别
    数组和指针
    C++初始化数据成员
    RSA算法原理
    C++四种cast
    百度笔试准备2
    百度笔试准备1
    百度面试准备
    C++的空类中默认产生哪些类成员函数
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3681061.html
Copyright © 2020-2023  润新知