zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    思路分析:
    我是先写了一个函数用于计算一个数字的下一个数字。计算过程是依次遍历当前数字统计相等的个数。

    C++演示样例代码:

    class Solution
    {
    public:
        //依据当前的number计算下一个number
        string countNext(string number)
        {
            string::size_type length = number.length();
            size_t count = 1;//记录同样数字的个数
            size_t index = 0;//遍历number的伪指针
            char curnum;//暂时保存当前的数字
            string result;//终于结果
            //这层循环控制对number的遍历
            while (index < length)
            {
                curnum = number[index];
                //这层循环寻找同样数字并统计个数
                while (index < length)
                {
                    //注意这里的index要先++然后进行比較推断,要不然会引起数组越界等问题
                    if (index++ != length && curnum == number[index])
                    {
                        //假设当前数字和其后的数字相等count++,统计有多少个当前数字
                        count++;
                    }
                    else
                    {
                        //假设不相等就将count和curnum存入结果字符串中
                        result.push_back(count + '0');
                        result.push_back(curnum);
                        count = 1;
                        break;
                    }
                }
            }
            return result;
        }
    
        string countAndSay(int n)
        {
            string number = "1";
            for (int i = 1; i < n; i++)
            {
                number = countNext(number);
            }
            return number;
        }
    };

    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    Python 中的map函数,filter函数,reduce函数
    编程中,static的用法详解
    C++ list容器系列功能函数详解
    python中的configparser类
    310实验室OTL问题----将写好的C++文件转换成Python文件,并将数据可视化
    310实验室OTL问题
    常量指针、指针常量、指向常量的指针常量
    Iterator迭代器的相关问题
    struts2中action中的通配符
    struts2访问servlet API
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4883058.html
Copyright © 2011-2022 走看看