zoukankan      html  css  js  c++  java
  • leetcode-38-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
    

    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.

    Example 1:

    Input: 1
    Output: "1"

    Example 2:

    Input: 4
    Output: "1211"

    要完成的函数:

    string countAndSay(int n) 

     

    代码:

    #include<string>
    #include<sstream>
        string int2str(int &i)//实现从int到string的转换
        {
            string s;
            stringstream ss(s);
            ss << i;
            return ss.str();
        }
        int count(string a,int b,int index)//在a中,从index这个位置开始,有多少个数字为b的,返回这个数量
        {
            int result=0;
            for(int i=index;i<a.size();i++)
            {
                if(a[i]==b)
                result++;
                else
                break;
            }
            return result;
        }
        string countAndSay(int n) //主要函数
        {
                string result="1";
            string result1;
            int result2;
            if(n==1)
            {
                return result;
            }
            while(--n)
            {
                int i=0;
                result1="";
                while(i<result.size())
                {
                    result2=count(result,result[i],i);
                    result1+=int2str(result2);
                    result1+=result[i];
                    i+=result2;
                }
                result=result1;
            }
            return result;
        }

    说明:

    1、这道题可能有的朋友不太明白题目在讲什么,说一下。

    首先,n=1的时候,输出“1”的序列。

    n=2的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“1”个“1”,所以输出“11”的序列。

    n=3的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“2”个“1”,所以输出“21”的序列。

    n=4的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的2,答案是“1”个“2”,所以输出12;数一下上一个序列中有多少个连续的1,答案是“1”个“1”,所以输出11。合起来就是“1211”。

    n=5的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“1”个“1”,所以输出“11”,数一下上一个序列中有多少个连续的2,答案是“1”个“2”,所以输出“12”,数一下上一个序列中有多少个连续的1,答案是“2”个“1”,所以输出“21”。合起来就是“111221”。

    看明白之后,本题采用最暴力的方法去做,定义了三个函数。每个函数的功能都在注释中写了。自己跑一遍应该就看出来了。

     

    2、c++的int2str在c++11中可以to_string(int)输出,比如cout<<to_string(123)+"908"<<endl;可以得到123908的输出。

    但在c++11之前,就要使用#include<sstream>中的方法,像本文那样使用就可以了。

  • 相关阅读:
    关于php,python,javascript文件或者模块导入引入的区别和联系
    es6在网页中模块引入的方法
    pip3 升级失败的解决方法!亲测有效
    php 简单的学习GD库绘制图片并传回给前端实现方式
    session与cookie的区别以及HTML5中WebStorage理解
    二次开发项目集合
    php微信公众号开发入门小教程
    安装运行mariadb时错误:gtid_slave_pos
    发测试 HTML/FILE/MYSQL/动态 20151120
    百度浏览器 自动弹窗!
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8709370.html
Copyright © 2011-2022 走看看